0

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?

2
  • remove var jsonString = JSON.stringify(myArray); and try again Commented Oct 18, 2017 at 9:57
  • 1
    Without digging into your code: "The array is correctly submitted" Did you verify this assumption with a Network Debugging Tool in your browser? If YES, then $_POST can't be empty, double check the target php file. If NO, check the network traffic, you'll find the error there. Commented Oct 18, 2017 at 9:59

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

@NineCattoRules did you fix the three things I told you to ?
@NineCattoRules can you please try to dump $_POST['data'] without decoding it ?
That was my fault...I have this warning json_decode() expects parameter 1 to be string, array given so I need to encode first right?
When sending from javascript to the server, you don't need JSON. If you REALLY WANT to use JSON, you need to return var jsonString = JSON.stringify(myArray); , then send that instead of "myArray" and then decode it. It's overkill though - POST can send variables
@NineCattoRules you don't need to encode it and then decode it. Just use the variable directly. $_POST['data'] contains what you need.
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.