2

I've got a JavaScript array named seat with many values in it.

As follows,I've serialized to be sent to a php file named confirm.php.

$('btnsubmit').click(function() {
  var seat = [];
  var seatar = JSON.stringify(seat);
  $.ajax({
    method: "POST",
    url: "confirm.php",
    data: seatar
  })
})

And this is the code in my php file.

$seatarr = "";
if(isset($_POST['data']))
{
    $seatarr = $_POST["data"];
    print_r($seatarr);
}

I've tried with my level best, looking at the previous questions asked on this section. But no matter how hard I try to fix it, this code never works. Why not?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Akila Ranasinghe
  • 167
  • 1
  • 13

2 Answers2

4

You're just sending raw JSON, but you're expecting to get a URI-encoded form with a data field in it. You can get that if you change your ajax call to use data: {data: seatar}:

$('btnsubmit').click(function() {
  var seat = [];
  var seatar = JSON.stringify(seat);
  $.ajax({
    method: "POST",
    url: "confirm.php",
    data: {data: seatar}
  })
});

jQuery will automatically turn that object into a URI-encoded submission with a single field in it.

Then use json_decode if you want to parse it on the server:

if(isset($_POST['data']))
{
    $seatarr = json_decode($_POST["data"]);
    print_r($seatarr);
}

Also, as Mr. Blue pointed out, your button selector is probably incorrect. You have $('btnsubmit') which is looking for a <btnsubmit>...</btnsubmit> element. You probably meant $("#btnsubmit") (if you have id="btnsubmit" on the button) or $("[name=btnsubmit]") (if you have name="btnsubmit" on the button).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • For the OP, you can turn the JSON object in to an associative array via the default parameter that [`json_decode`](http://php.net/manual/en/function.json-decode.php) takes, just set it to true. – Script47 May 01 '18 at 09:03
  • 1
    ....alternatively you can leave the javascript as-is and read the raw data on the PHP side - https://stackoverflow.com/questions/8945879/how-to-get-body-of-a-post-in-php – symcbean May 01 '18 at 09:31
  • @symcbean: Indeed, though you'd want to add `contentType: "application/json"` (and fix the selector). – T.J. Crowder May 01 '18 at 09:33
0

Another solution can be to rewrite the data like this:

seatar = $(this).serialize() + "&" + $.param(seatar);

and decode like T.J Crowder did propose:

if(isset($_POST['data']))
{
    $seatarr = json_decode($_POST["data"]);
    print_r($seatarr);
}