Reputation: 2428
I need to submit an array of JSON objects
[{"id":"321","position":"2"},{"id":"359","position":"3"}]
So I tried
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': _token
}
});
table.on( 'row-reorder', function ( e, diff, edit ) {
var myArray = [];
for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
var rowData = table.row( diff[i].node ).data();
myArray.push({
id: rowData.id, // record id from datatable
position: diff[i].newData // new position
});
}
var jsonString = JSON.stringify(myArray);
//jsonString output an array as the one above
$.ajax({
url : "/requests/setOrder.php",
type : 'POST',
data : jsonString,
dataType: 'json',
success : function ( json )
{
$('#example23').DataTable().ajax.reload(); // now refresh datatable
$.each(json, function (key, msg) {
// handle json response
});
}
});
});
In setOrder.php
I would like to dump
my array so I tried:
$result = json_encode($_POST);
var_dump($result);
The array is correctly submitted, so why the response is empty?
Upvotes: 0
Views: 101
Reputation: 1940
First you need to remove var jsonString = JSON.stringify(myArray);
- the data should not be sent as "json" in the "data" field - jQuery does that for you
Before sending the data, you should assign it to a variable:
data : {data: myArray}
Also in the backend, you should use $result = json_decode($_POST['data']);
Your complete code should be:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': _token
}
});
table.on( 'row-reorder', function ( e, diff, edit ) {
var myArray = [];
for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
var rowData = table.row( diff[i].node ).data();
myArray.push({
id: rowData.id, // record id from datatable
position: diff[i].newData // new position
});
}
//jsonString output an array as the one above
$.ajax({
url : "/requests/setOrder.php",
type : 'POST',
data : {data: myArray},
dataType: 'json',
success : function ( json )
{
$('#example23').DataTable().ajax.reload(); // now refresh datatable
$.each(json, function (key, msg) {
// handle json response
});
}
});
});
and in PHP: If you json.stringify your data before sending it, you will need to decode it here. However, You don't need to send JSON when sending to the server. You will, however receive JSON in return.
$result = $_POST['data'];
var_dump($result);
Upvotes: 1
Reputation: 8348
First set your data in the ajax like this:
data :{jsonString: jsonString},
Then in your php file set $_post to a variable like
$myVar=$_POST['jsonString'];
And you got your response like that
Upvotes: 0