Upate table with AJAX in Laravel 5.3 not working - php

I trying to use an AJAX PUT request to update a row in my database and I am trying to send the request to my controller. This is my AJAX call:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leased').val();
var truckModel = $('#truck-model').val();
$.ajax({
url: 'editTruck',
type: 'put',
data: {
truckNo: truckNo,
truckOwner: truckOwner,
vehicle_number: vehicle_number,
capacity: capacity,
end_of_insurance: end_of_insurance,
end_of_kteo: end_of_kteo,
truckCode: truckCode,
leased: leased,
truckModel: truckModel
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(){
console.log('success');
},
error: function(){
console.log('something went wrong');
}
});
});
So far so good. If I console.log() my data is seems I can get them from the form. I am using Laravel Collective for the form:
{!!Form::open(array('action' => ['Trucks#editTruck'], 'method' => 'put')) !!}
and my route is the following:
Route::put('/editTruck', 'Trucks#editTruck',function(){ });
Now I am using Request $request in the parameters of the controller but somehow it looks like I cannot get the incoming values. For example the following var_dump will say NULL.
public function editTruck(Request $request)
{
$data = $request->input('truckNo');
var_dump($data);
}
Same happens if I use
$data = $request->truckNo;
instead. So I am wondering how can I get the values that are been sent to my controller with my AJAX call? Why am I getting NULL values?
What I was planning to do is:
public function editTruck(Request $request)
{
$singleTruck = Truck::find($request->truckNo);
$singleTruck->truckNo = $request->input('truckNo');
$singleTruck->truckOwner = $request->input('truckOwner');
........
$singleTruck->save();
}

You can find the answer here:
https://laravel.io/forum/02-13-2014-i-can-not-get-inputs-from-a-putpatch-request
You should change your form method and method inside your js code to "post", and add extra field "_method" = "PUT"
probably it can help.

OK I found it. Looks like the AJAX was malformed. So here is how it should be written:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#vehicle_capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leasing').val();
var truckModel = $('#truck-model').val();
var outGoingData = {
'truckNo': truckNo,
'truckOwner': truckOwner,
'vehicle_number': vehicle_number,
'capacity': capacity,
'end_of_insurance': end_of_insurance,
'end_of_kteo': end_of_kteo,
'truckCode': truckCode,
'leased': leased,
'truckModel': truckModel,
};
var data = JSON.stringify(outGoingData);
$.ajax({
url: 'editTruck',
type: 'POST',
data: data, <!-- The error was here. It was data: {data}-->
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(response){
alert("The data should be "+ response);
},
error: function(){
console.log('skata');
}
});
});

Related

Receive data from MySQL database without reloading the page

I am trying to retrieve data from the database, but when the get parameter appears in the address bar, there is no change on the page, so I have to refresh the page to receive the data, instead of receiving it without refresh/reload.
Route:
Route::get('writers/{orders?}/{number?}', ['as'=>'writers','uses'=> 'HomeController#writers']);
Controller:
public function writers($order='all',$num=10){
$dm = new DataModel();
$orders = $dm->getCertainWriters($num);
$this->certainOrders =$orders;
return view('writers')->with(array('title'=>'Writers','data'=>$this->certainOrders,));
}
Method:
public function getCertainWriters($orders = 'all'){
$data = DB::select("SELECT * FROM `writers` WHERE `completed_orders` > '$orders' ");
return $data;
}
AJAX:
$("#ajax-orders").change(function(e) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "GET",
url: url,
dataType:"html",
headers: {
'X_CSRF_TOKEN':CSRF_TOKEN,
'Content-Type':'application/json'
},
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
$(form).submit(e);
var orders = $('select').val();
window.history.pushState("writer", "orders", "/writers/orders/"+orders);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

jQuery+PHP. Request/Response

I would search for the solution, but I don't know what exactly do I have to search.
The task is to grab texts with ID's (#ftext_1,..._2,..._3,..._4) in html file and send them to php file. After some manipulation with texts in php file I have to insert them back into their ID's in html file.
Here is the code:
var text_1_Replace = $('#ftext_1').text();
var text_2_Replace = $('#ftext_2').text();
var text_3_Replace = $('#ftext_3').text();
var text_4_Replace = $('#ftext_4').text();
$('#ID').on('click', function(){
var text= {
ftext_1: text_1_Replace,
ftext_2: text_2_Replace,
ftext_3: text_3_Replace,
ftext_4: text_4_Replace
}
var targetFile = 'ajax/file.php';
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text),
contentType: 'application/JSON'
}).done(function(data) {
console.log(data);
});
});
How do I edit .done function to place new texts in their old ID's(#ftext_1,..._2,..._3,..._4)? The variable with texts array is $result.
so the answer is :
}).done(function(data) {
var text = JSON.parse(data);
var text1 = text.ftext_1;
var text2 = text.ftext_2;
var text3 = text.ftext_3;
var text4 = text.ftext_4;
$('#ftext_1').text(text1);
$('#ftext_2').text(text2);
$('#ftext_3').text(text3);
$('#ftext_4').text(text4);
So, the last update for the topic: The real and nice answer is:
.done(function(data) {
var text = JSON.parse(data);
$.each(text, function(i, val){
$("#" + i).text(val);
});
This code is the solution to my question in this topic. Thank you all, who responded!
The best for you would be send named property that looks like this
$.ajax({
method: 'post',
url: targetFile ,
data: {data: text},
dataType: "json",
success: function(response){
$.each(response, function(element){
$("#"+element.name).text(element.text);
});
}
});
Then in your php you could easily iterate data from post
<?php
$data = $_POST['data'];
$response = [
];
foreach($data as $elementName => $text){
// some text management
$response[] = ['name' => $elementName, 'text' => $text];
}
return json_encode($response);
When you change your received values in php you put them in an array so that you
can call it later easily
PHP
$values = array("one"=>5,
"two"=>"something",
"three"=>$something);
echo json_encode($values);
You need to add
dataType:'json'
in Jquery since you're returning json
JQuery
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text), # or data: {"value1":value,"value2":value2},
contentType: 'application/JSON',
dataType:'json',
success: function(response){
console.log(response.one); #Will console 5
console.log(response.two); #Will console "something"
console.log(response.three); #Will console whatever $something holds in php
}
});
You can call it however you want it (response) or (mydata)...
And then you just type response.yourdata (that you declared in php)

How to pass array from ajax to php?

I'm trying to pass array from ajax to php (controller).
What is wrong with second code as var_dump($data) of first code returns appropriate content and second returns NULL?
FIRST. GOOD.
function myFunction() {
var elementy = document.getElementsByClassName('inputISBN');
var data = elementy[0].value;
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
SECOND. BAD
function myFunction() {
var elementy = document.getElementsByClassName('inputISBN');
var data = [];
data[elementy[0].name] = elementy[0].value;
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
THIRD. UGLY
var elementy = document.getElementsByClassName('inputISBN');
undefined
var data = [];
undefined
data[elementy[0].name] = elementy[0].value;
"667"
Third one is line by line from the socond code written in browser console. And it's return what it should.
edit
and data is pulled out from here:
<input type="number" class="inputISBN" size="2" name="exampleName"
value="666" onchange="myFunction()">
When passing an array to PHP, you want to include the array indicator: []. I thi8nk you need an Object: {}.
function myFunction() {
var elementy = $('.inputISBN');
var data = {};
$.each(elementy, function(){
data[$(this).attr('name')] = $(this).val();
})
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
At this point, you may also want to serialize the data (as was mentioned in the other answer by #Adelphia):
'data': JSON.stringify(data)
jsFiddle: https://jsfiddle.net/Twisty/cw77ann7/
You can call it in PHP: print_r($_POST['data']);
You want to pass your data variable to PHP, which is an array, right? Why not data = JSON.stringify(data); and then on PHP's side, $data = json_decode($_POST['data'], true);
function myFunction() {
var elementy = document.getElementsByClassName('inputISBN');
i = elementy.length;
data = [];
while(i--) data[elementy[i].name] = elementy[i].value;
data = JSON.stringify(data);
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}

Cannot get variable to send using $.ajax({data}) to PHP

I have tried these JS code combos:
var aion_settings = [];
function aion_save_settings(){
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: function(){
return aion_settings;
},
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
and...
function aion_save_settings(){
var aion_settings = [];
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: aion_settings,
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
..and
var aion_settings = [];
function aion_save_settings(){
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: aion_settings,
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
..and these combos with:
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:aion_settings,
success:function(result){
console.log(result);
}
});
On this JQuery page it even has this example:
var xmlDocument = [create xml document];
var xmlRequest = $.ajax({
url: "page.php",
processData: false,
data: xmlDocument
});
xmlRequest.done(handleResponse);
On the receiving side, I have this PHP code:
$app->post('/save_settings',function() use ($app){
$aion_settings=$app->request()->post();
var_dump($aion_settings);
//Save the aion_settings
if(aion_logged_in_user_super()){
global $aion_db;
if(is_array($aion_settings)) foreach($aion_settings as $setting_key => $setting){
//Get the setting's ID
$current_setting = array();
$current_setting = $aion_db->queryFirstRow("SELECT id FROM settings WHERE setting_key=%s",$setting_key);
if(!isset($current_setting['id'])) $current_setting['id']=NULL;
$aion_db->insertUpdate('settings',array(
'id'=>$current_setting['id'],
'setting_key'=>$setting_key,
'value'=>serialize($setting)
));
}
}
});
The aion_settings is setup correctly just before the $.ajax request is sent. But, the object settings is not caught on the PHP side, though other_data is caught? The last line below shows the object ready via console.log but not set via $.ajax. I'm stumped, any help?
The data parameter of your $.ajax function should have the following format:
data: {
'settings': aion_settings,
'other_data': 'Other Data'
},
This is how I fixed it:
JS Side:
function aion_save_settings(){
var aion_settings = new Object();
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:aion_settings,
success:function(result){
console.log(result);
}
});
}
PHP Side:
$app->post('/save_settings',function() use ($app){
$aion_settings=$app->request()->post();
var_dump($aion_settings);
//Save the aion_settings
if(aion_logged_in_user_super()){
global $aion_db;
if(is_array($aion_settings)) foreach($aion_settings as $setting_key => $setting){
//Get the setting's ID
$current_setting = array();
$current_setting = $aion_db->queryFirstRow("SELECT id FROM settings WHERE setting_key=%s",$setting_key);
if(!isset($current_setting['id'])) $current_setting['id']=NULL;
$aion_db->insertUpdate('settings',array(
'id'=>$current_setting['id'],
'setting_key'=>$setting_key,
'value'=>serialize($setting)
));
}
}
});
Please compare with my question above.

Zend and Jquery (Ajax Post)

I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.

Categories