Ajax send data with string name - php

I apologise if this was already answered, but I haven't found an answer in 70k+ results..
I want to send data like this:
function _post(params) {
var func = params['func']; // -> 'getUserDetails'
$.ajax({
url: "crossroad.php",
type: "post",
data: { func : params },
cash: false,
complete: function(respond){
console.log(respond);
}
});
}
m = {};
m['func'] = 'getUserDetails';
m['id'] = '123456';
_post(m);
But with this code, php gets
$_POST['func']
I want string that I am sending to be named as params['func'] and in this case I want to receive in php
$_POST['getUserDetails']
How can I achieve this ?

You need to create object
var requestParams = {};
And then setup it property like
requestParams[params['func']] = '';// your data to send
//or
requestParams[params['func']] = params['id'];// your data to send
And then put into ajax data property
data: requestParams,

The problem here is that func is a valid key identifier, so although you are expecting func to be substituted for the parameter you passed in, you are actually declaring a property of your data object called func.
To get around this issue, create a new object, and pass it in like this:
function _post(params) {
var func = params['func']; // -> 'getUserDetails'
var obj = {};
obj[func] = params;
$.ajax({
url: "crossroad.php",
type: "post",
data: obj,
cash: false,
complete: function(respond){
console.log(respond);
}
});
}

function _post(params) {
var func = params['func']; // -> 'getUserDetails'
var obj = {};
obj[func] = params['id'];
$.ajax({
url: "crossroad.php",
type: "post",
data: obj,
cash: false,
complete: function(respond){
console.log(respond);
}
});
}
m = {};
m['func'] = 'getUserDetails';
m['id'] = '123456';
_post(m);

Related

Upate table with AJAX in Laravel 5.3 not working

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');
}
});
});

I have arrays stored in a json object, I send them using ajax call to the server side, how to access the data?

$scope.addQunatity = function(){
var url="../php/mainPageFacture.php";
// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];
var func="addQunatity";
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
data = JSON.stringify(data);
var options = {
type : "get",
url : url,
data: {data:data},
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
Here is my php code that will receive the Json object
function addQunatity(){
$quan_cls_crt = $_GET["quan_cls_crt"];
$quan_piece = $_GET["quan_piece"];
$itemId=$_GET['itemId'];
$dechargementNote=$_GET['dechargementNote'];
}
I expect to receive the json arrays and store them in php variable in order to use the in the query later on, but i have no idea how to access the arrays in the json object
You don't have to stringify the data, just send it as it is - the json data type causes jQuery to JSON-encode it for you. Don't make another object.
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
var options = {
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
<?php
$received_data = file_get_contents('php://input');
$data = json_decode($received_data);
//Here now you can access
$variable_name = $data['keyname']; //this means instead of $_GET or $_POST or $_REQUEST
?>
You can access received json data to php using the file_get_contents('php://input'); method..
Dont stringify the data. Use your same code and remove the stringify line.
var url="../php/mainPageFacture.php";
// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];
var func="addQunatity";
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
var options = {
type : "get",
url : url,
data: {data:data},
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
In the PHP side, like you have done -
$quan_cls_crt = $_GET["quan_cls_crt"];
$quan_piece = $_GET["quan_piece"];
$itemId=$_GET['itemId'];
$dechargementNote=$_GET['dechargementNote'];
And to access each of the values from array you can simply do that with $quan_cls_crt[0] or $quan_cls_crt[1]

how do i pass datastring parameter for jquery's .ajax() function properly?

var username = $('#username').val();
var dataString = 'username=' + username;
$.ajax({
type: "POST",
url: "signinout.php",
data: dataString,
success: function() {
$('.user').html('<span>Welcome <span id="loggedUser">' + username + '</span>!</span> <a id="signOut" onclick="window.location.reload()">SIGN OUT</a>');
}
});
using the above code, my username variable is not being passed on correctly, I'm assuming something is wrong with the way I coding the datastring parameter but I'm not sure how to do it correctly.
Below is the php code that I am using in signinout.php to insert the username into the database, the username field is not being entered with each new entry into the database.
$username = protect($_POST['username']);
$time = time();
$sql = "INSERT INTO users
(username, join_date)
VALUES
('$username', '$time')";
$result = mysqli_query($cn, $sql) or
die(mysqli_error($cn));
Your "best" datastring depends on your needs in the server side part. As an example, this jquery-ajax call send a object to a server side action (PHP) :
var mydata = null;
mydata = "hellostring=1";
mydata = { title: "some" , value: "thing" };
mydata = [1,2,3];
$.ajax({
cache: false, type: 'post', async: true,
data: mydata,
url: 'some-script.php',
success: function(resp){
console.log("OK",resp);
},
error: function(e){
console.log(e.responseText);
}
});
As result, in your serve side you may have this script, which will return the same as you send:
// some-script.php
<?php
echo print_r($_POST,true);
?>
The outputs, for each kind of data (see the mydata variable) is:
Case: mydata = "hellostring=1";
Array( [hellostring] => "1" )
this mean, in serverside, you can:
$_123 = $_POST["hellostring"];
Case mydata = { title: "some" , value: "thing" };
As result, you get:
Array
(
[title] => some
[value] => thing
)
So you can:
$title = $_POST['title']; $value = $_POST['value'];
Case mydata = [1,2,3];
Surprise, this doesnt work, :) , you should wrap it, in this form:
mydata = { some : [1,2,3] }
So, you can proceed in your server-side the same as the previous case.
Note:
To avoid get hacked: (PHP CASE example) filter your input using:
http://php.net/manual/es/function.filter-input.php
More
In order to have a more advanced data handling in your server side part, (that is: in the script who receive the ajax request) , you can make usage of json, in this way:
Let start by supposing you are sending a object via javascript:
// in your client part,
mydata = { title: "some" , value: "thing", mydog: "sammy" };
..do your ajax call stuff here..
And, in your server side:
<?php
// some-script.php
$obj = json_decode(file_get_contents('php://input'));
echo $obj->title; // output: "some"
echo $obj->value; // output: "thing"
echo $obj->mydog; // output: "sammy"
?>
try passing it as a regular javascript object
var dataObj = {'username': username};
$.ajax({
type: "POST",
url: "signinout.php",
data: dataObj,
Try using data: "username="+username, instead
var username = $('#username').val();
$.ajax({
type: "POST",
url: "signinout.php",
data: "username=" + username,
success: function() {
$('.user').html('<span>Welcome <span id="loggedUser">' + username + '</span>!</span> <a id="signOut" onclick="window.location.reload()">SIGN OUT</a>');
}
});

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 }
});
}

How to pass a nested PHP-Array via AJAX-Post?

I have a PHP-Script that expects:
$_REQUEST['asdf']['bsdf']['csdf']
to be set when it is called, and I cannot change this.
I want to call this PHP-Script via ajax:
myurl = 'example-url.com';
myid = $(this.$element).attr('id'); //gets the id of a textfield: csdf
value = 'somevalue';
$.ajax({type: 'POST',
url: myurl,
data: {'asdf[bsdf][myid]': value},
success: function (data) {
/* blabla */
}
});
It does not work though, because the var "myid" is not filled with the supposed value "csdf".
Can someone help me how to do this?
PS: I cannot access the PHP-File, so no changes in structure possible...
Try something like this:
var myurl = 'example-url.com';
var myid = $(this.$element).attr('id'); //gets the id of a textfield: csdf
var value = 'somevalue';
var param = {};
param[myid] = value;
$.ajax({type: 'POST',
url: myurl,
data: {'asdf[bsdf]' : param},
success: function (data) {
}
});
You can build the param object outside the data you pass via the ajax call to keep the correct key in place.
in JS
... {
...
data: {[['first', 'array', 'nested'], 'other', 'in', 'parent', 'array']},
...
}
In PHP getting the POST vars is with other sentence
http://php.net/manual/en/reserved.variables.post.php

Categories