Hello i have component Vue, taskdone.php and todo.json.
At moment i can create new tasks from input in vue(frontend), send it on php(backend) and store it in todo.json.
I m trying to add feature that i click on text with the task and the value "completed" change from true to false but dont work.
Can someone explain me the fixes and the reason ?
Thanks for your time
todo.VUE
<script >
import axios from 'axios';
const API_URL = "http://localhost/";
export default {
data(){
return{
task : "",
todoList : []
}
},
methods: {
getAll(){
axios.get(API_URL + "api.php")
.then(res => {
const data = res.data;
this.todoList = data;
});
},
addNew(e){
e.preventDefault();
const params = { params: {
"newTask" : this.task
}};
axios.get(API_URL + "newtask.php",params)
.then(() => {
this.getAll();
})
this.task = "";
},
taskDone(i){
const params = { params: {
"id" : i
}}
axios.get(API_URL + "newtask.php", params)
console.log(i);
}
},
mounted(){
this.getAll();
}
}
</script>
<template>
<form action="" #submit="addNew">
<label for="">Inserisci task: </label>
<input type="text" v-model="task">
<input type="submit" value="Add" >
</form>
<ul>
<li v-for="(task,index) in todoList" :key="index" :class="task.completed == true ? 'taskDone': ''" #click="taskDone(index)">
{{ task.text }}
{{ task.completed }}
</li>
</ul>
</template>
<style scoped>
.taskDone{
text-decoration:line-through;
}
</style>
taskdone.php
<?php
header("Access-Control-Allow-Origin: http://localhost:5173");
header("Access-Control-Allow-Headers: X-Requested-With");
header("Content-Type: application/json");
$id = $_GET["id"];
$jsonTodoList = file_get_contents("todo.json");
$todoList = json_decode($jsonTodoList);
$todoList=$todoList[$id]["completed"] = !$todoList[$id]["completed"];
$jsonTodoList = json_encode($todoList);
file_put_contents("todo.json" , $jsonTodoList);
todo.json
[
{"text":"take a break",
"completed":false
},
{"text":"buy a coffee",
"completed":false
}
]
Related
i am trying to submit a form with laravel and vuejs in a component like below :
<form action="#" #submit.prevent="submitMobile">
<div class="container my-5 z-depth-1">
<!-- Form -->
<form class="" action="">
<!-- Section heading -->
<div class="input-group">
<input class="form-control send-sms-btn" name="mobile"
v-validate="'required:11'" placeholder="_ _ _ _ _ _ _ _"
aria-label="Enter your email address"
aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn-theme btn btn-md btn-primary rounded-right m-0 px-3 py-2 z-depth-0 waves-effect"
type="submit" id="button-addon2">submit
</button>
</div>
</div>
</form>
</form>
and here is my vuejs :
export default {
props: [
],
data: function () {
return {
}
},
methods: {
sendContactFormServer() {
axios({
method: 'POST',
url: '/customer/send-sms',
data: {
"mobile": this.form.mobile,
},
headers: {
'Content-Type': 'appllication/json',
'Accept': 'application/json',
}
})
.then(window.location.href = "/")
.catch(error => console.log(error))
},
submitMobile: function() {
this.$http.post('/customer/send-sms', this.formData).then(function(response) {
console.log(response);
}, function() {
console.log('failed');
});
}
}
}
i tried 2 functions but both of them returns me to the same page with the query string of the input i have send . now i want to know how can i submit this form without refreshing the page . thanks in advance
try this.$router.push()
https://router.vuejs.org/guide/essentials/named-routes.html
submitMobile: function() {
this.$http.post('/customer/send-sms', this.formData).then(function(response) {
this.$router.push({
name: "route_name", // tis route name you need to add
query: { mobile: this.mobile },
});
}, function() {
console.log('failed');
});
}
I need to update the data from MySQL DB using AngularJS + PHP.
Dashboard.html is my first page I just give only two field: name and position, and I fetch the data from DB using ng-repeat after fetch the code the user will click the edit button it will redirect to the edit.html page with the same fields: name and position. Help me to fetch that name and position data in edit.html page
Dashboard.html
<div ng-app="myapp" ng-controller="usercontroller">
<table>
<th>Name</th>
<th>Position</th>
<tbody>
<tr ng-repeat="x in names">
<td>{{x.name}}</td>
<td>{{x.position}}</td>
<td>
<span class="glyphicon glyphicon-edit" ng-click="updateData(x.name, x.position)" ></span>
</td </tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var app = angular.module("myapp", []);
app.controller("usercontroller", function($scope, $http) {
$scope.updateData = function(name, position) {
$scope.name = name;
$scope.position = position;
$scope.btnName = "Update";
}
});
</script>
This is my edit.html page and am using ng-model to bind the data from
dashboard.html, but it is not binding. And I click the update button the data have to update with id, and I mentioned my PHP file also.
My DB name sample and table named demo.
Edit.html
<div ng-app="myapp" ng-controller="EditController">
<form name="form">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" ng-model="name" /> {{name}}
</div>
<div class="form-group">
<label for="position">Position</label>
<input class="form-control" type="text" name="position" ng-model="position" />
</div>
<input type="submit" name="btnUpdate" class="btn btn-success" ng-click="update_data()" value="{{btnName}}">
</form>
<script>
var app = angular.module("myapp", []);
app.controller("EditController", function($scope, $http) {
$scope.btnName = "Update";
$scope.update_data = function() {
$http.post(
"edit.php", {
'name': $scope.name,
'position': $scope.position,
'btnName': $scope.btnName
}
).success(function(data) {
alert(data);
$scope.name = null;
$scope.position = null;
$scope.btnName = "Update";
});
}
});
</script>
Edit.php
<?php
$connect = mysqli_connect("localhost", "root", "", "sample");
$data = json_decode(file_get_contents("php://input"));
if (count($data) > 0) {
$name = mysqli_real_escape_string($connect, $data->name);
$position = mysqli_real_escape_string($connect, $data->position);
$btn_name = $data->btnName;
if ($btn_name == 'Update') {
$id = $data->id;
$query = "UPDATE demo SET name = '$name',position = '$position' WHERE id = '$id'";
if (mysqli_query($connect, $query)) {
echo 'Updated Successfully...';
} else {
echo 'Failed';
}
}
}
?>
You have two different controllers: usercontroller and EditController. Once you leave one and enter another, you lose your bindings. So ng-model="name" in once controller is completely different from ng-model="name" in the second controller.
To make sure that they are the same, you need to create a service that will share data between controllers. You can make it like a simple storage service without any bindings.
When you want to update the data, you need to save it in the service as well. And whenever you want to edit it, you need to pull that data out of it, and populate your models.
Example of such service:
app.service("storageService", function() {
this.data = {};
this.set = function(name, position, btnName) {
this.data = {
"name": name,
"position": position,
"btnName": btnName
};
}
this.get = function() {
return this.data;
}
this.clear = function() {
this.data = {
"name": null,
"position": null,
"btnName": null
};
}
})
The you can inject it into your controllers and use it's functions:
usercontroller
app.controller("usercontroller", function($scope, $http, storageService) { // <-- note the injection
$scope.updateData = function(name, position) {
$scope.name = name;
$scope.position = position;
$scope.btnName = "Update";
storageService.set($scope.name, $scope.position, $scope.btnName); // saving data
}
});
EditController
app.controller("EditController", function($scope, $http, storageService) {
var d = storageService.get(); // loading data
$scope.name = d.name;
$scope.position = d.position;
$scope.btnName = "Update"; // = d.btnName;
$scope.update_data = function() {
$http.post(
"edit.php", {
'name': $scope.name,
'position': $scope.position,
'btnName': $scope.btnName
}
).success(function(data) {
alert(data);
$scope.name = null;
$scope.position = null;
$scope.btnName = "Update";
});
}
});
I am creating a Ticket Reservation System and I want to check data availability from the Database. As usual, I used HTML form and when someone tries to insert data which is already in the database , I want to show them a message as "Data Already Have". And If data is unique , I want to insert into the database. But , when I click Submit button, nothing happens. ( Seat Number = Items )
In the console of the browser shows these errors -
POST http://localhost/FinalProject/public/seatprocess 500 (Internal
Server Error) XHR failed loading: POST
"http://localhost/FinalProject/public/seatprocess"
In Network tab -> Response shows like this -
{
"message": "Object of class Illuminate\\Database\\Query\\Builder could not be converted to string",
"exception": "ErrorException",
"file": "D:\\wamp64\\www\\FinalProject\\app\\Http\\Controllers\\SeatsController.php",
"line": 42,
"trace": [
{
"file": "D:\\wamp64\\www\\FinalProject\\app\\Http\\Controllers\\SeatsController.php",
"line": 42,
"function": "handleError",
"class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
"type": "->"
},
And this is continuesly going. May be my seatprocess function is wrong. But , I have no idea how to Fix it.
Form and Seat Structure Image
How can I Fix this ??
Here is my Seats.blade.php
<form class="form-horizontal" id="form1" method="POST" action="{{ route('seatsinsert') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="dt"> <br>
<h4> <span id="success_message" class="text-success"></span> </h4>
<div class="form-group row">
<label for="example-date-input" class="col-2 col-form-label">Select Date :</label>
<div class="col-10">
<input class="form-control" type="date" name="date" placeholder="mm-dd-yyyy" id="example-date-input">
</div>
</div>
<div class="form-group">
<label for="exampleSelect1">Select Time :</label>
<select name="st" class="form-control" id="exampleSelect1">
<option>10.30 am</option>
</select>
</div>
</div>
<h2 style="font-size:1.2em;font-family: Times New Roman;"> Choose seats by clicking below seats :</h2>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="width:600px;text-align:center;overflow:auto"> <br>
<input type="submit" class="btn btn-primary" id="btnShowNew" value="Continue"> <br><br>
<span id="availability"></span>
<script type="text/javascript">
$(function () {
$('#btnShowNew').click(function (e) {
e.preventDefault();
var items = [];
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
items.push($(this).attr('title'));
});
console.log(items);
// $(location).attr('href', 'Seats');
$.ajax({
url:'{{ route('seatprocess') }}',
type:"POST",
data:{
_token: "{{ csrf_token() }}",
items: JSON.stringify(items),
date: $('input[name=date]').val(),
st: $('select[name=st]').val()},
success:function(data)
{
if(data !== '0')
{
$('#availability').html('<span class="text-danger">Seats not available</span>');
$('#btnShowNew').attr("disabled", true);
}
else
{
//$('#availability').html('<span class="text-success">Seats Available</span>');
$.ajax({
type: "post",
url: "{{ route('seatsinsert') }}",
data: {
_token: "{{ csrf_token() }}",
items: JSON.stringify(items),
date: $('input[name=date]').val(),
st: $('select[name=st]').val()},
success: function(data){
$("form").trigger("reset");
$('#success_message').fadeIn().html("Text");
}
});
$('#btnShowNew').attr("disabled", false);
}
}
});
}); //btnShowNew
}); //Final
</script>
</form>
Here is my SeatsController.php
public function seatsinsert(Request $request)
{
$date = $request->input('date');
$st = $request->input('st');
$items = $request->input('items');
$items = str_replace(['[', ']', '"'], '', $items);
$user = new Seats();
$user->date = $date;
$user->st = $st;
$user->item = $items;
$user->save();
}
public function seatprocess(Request $request)
{
//dd($request->all());
$items = $request->input('items');
$results = DB::table('seats')->where('item',$items);
echo $results;
}
}
Here are my Routes.
Route::post('seatsinsert',[
'uses'=> 'SeatsController#seatsinsert',
'as' => 'seatsinsert'
]);
Route::post('seatprocess',[
'uses'=> 'SeatsController#seatprocess',
'as' => 'seatprocess'
]);
You need to retrieve data in your response function with get like this before echo the $result variable.
This is the reason behind error in your console.
you have to change the line like this:
$results = DB::table('seats')->where('item',$items)->get();
Good day I want to use this json data to use the autocomplete of semantic ui. any Idea please. below is my code I saw in different sites.
record.json
{
records: [
{
idno: "PH00019404-1",
firstname: "CHERRY MAE"
},
{
idno: "PH00008381-2",
firstname: "LUZMIN"
}
]
}
My Html
<div class="ui search focus">
<div class="ui search icon input">
<input class="ui search" type="text" placeholder="Colors..." autocomplete="off">
<i class="search icon"></i>
</div>
<div class="results"></div>
</div>
My Javascript
<script type="text/javascript">
$(document).ready(function () {
$('.ui.search').search({
apiSettings: {
url: 'www.mysite.com/record.json',
minCharacters : 3,
onResponse: function(results) {
var response = {
results : []
};
$.each(results, function(index, item) {
response.results.push({
title : item.idno,
description : item.firstname
//url : item.html_url
});
});
return response;
},
},
});
});
</script>
I got the answer to this link. https://semantic-ui.com/modules/search.html#/examples
<script>
$('.ui.search')
.search({
apiSettings: {
url: 'http://localhost/views/api/members?q={query}'
},
fields: {
results : 'records',
description : 'name',
title : 'idno'
},
minCharacters : 3
})
;
</script>
I try to post data to laravel controller using ajax, but still get response null. My achievement is to post form data and return error message or success message.
I'm newbie in ajax and laravel framework please help me to solve the problem.
Here is the meta tag header:
<meta name="_token" content="{{ csrf_token() }}">
Here is the html form :
{{ Form::open(['id'=>'testimonial_form','url'=>URL::action("processing-give-testimonial"),'method'=>'POST']) }}
{{ Form::hidden('_method', 'PUT') }}
<div class="row marginbot-20">
<div class="col-md-6 xs-marginbot-20">
{{ Form::text('name',null, ['class'=>'form-control input-lg','placeholder'=>'Enter Name','id'=>'name']) }}
</div>
<div class="col-md-6">
{{ Form::email('email',null, ['class'=>'form-control input-lg','id'=>'email','placeholder'=>'Enter email','id'=>'email']) }}
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<select name="subject" id="subject" class="form-control" require="required">
<option value="ask">Ask Question / Information</option>
<option value="testimonial">Give Feedback / Testimonial</option>
</select>
</div>
<div class="form-group">
{{ Form::textarea('message',null,['id'=>'message','class'=>'form-control','rows'=>'4','cols'=>'25','placeholder'=>'message','id'=>'message']) }}
</div>
<!-- {{ Form::submit('Send Message',['id'=>'btnContactUs','class'=>'btn btn-skin btn-lg btn-block']) }} -->
{{ Form::button('Submit', ['class'=>'btn btn-skin btn-lg btn-block','id'=>'click']) }}
</div>
</div>
{{ Form::close() }}
Here is the ajax code :
$(function() {
$.ajaxSetup({
headers: {
'X-XSRF-Token': $('meta[name="_token"]').attr('content')
}
});
});
$(document).ready(function() {
$('#click').click(function() {
var formData = {
name : $('#name').val(),
email : $('#email').val(),
subject : $('#subject').val(),
message : $('#message').val(),
};
$.ajax({
type : "POST",
url : "{{ URL::action('processing-give-testimonial') }}",
data : formData,
beforeSend: function () {
alert('sure?');
},
success: function(data) {
console.log(data);
},
error: function() {
console.log('error');
}
});
});
});
Here is the controller :
public function create()
{
$inputs = array(
'name' =>Input::get('name'),
'email' =>Input::get('email'),
'subject' =>Input::get('subject'),
'message' =>Input::get('message')
);
//return "we reached here";
return Response::json("success");
/*if(Request::ajax()) {
return Response::json('success', 200);
} else {
return Response::json('failed', 400);
}*/
/* if(Request::ajax()) {
$data = Input::get('email');
//print_r($data);die;
if ($data != '') return Response::json('success',200);
else return Response::json('failed',400);
}*/
/*
$input = Input::get('name');
//$input = Input::get('_token');
if ($input == '') {
return Response::json('failed',400);
}
else {
return Response::json('success',200);
}*/
//if(!empty($input)) return Response::json(['data'=>'success']);
//else return Response::json('data',$input);
}
Here is the my route :
Route::post('give-testimonial',['uses'=>'TestimonialController#store','as'=>'processing-give-testimonial']);
Here is the filter.php :
Route::filter('csrf', function() {
$token = Request::ajax() ? Request::header('X-XSRF-Token') : Input::get('_token');
if (Session::token() != $token) {
throw new Illuminate\Session\TokenMismatchException;
} });
I'm guessing your routing is wrong. Try changing this route:
Route::post('give-testimonial',['uses'=>'TestimonialController#store','as'=>'processing-give-testimonial']);
to this:
Route::post('give-testimonial',['uses'=>'TestimonialController#create','as'=>'processing-give-testimonial']);