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?

3
  • It should be type: "POST" and not method Commented May 1, 2018 at 8:57
  • 1
    $('input[name="btnsubmit"]') ?? Commented May 1, 2018 at 8:57
  • 2
    @Dario: method was added in jQuery v1.9.0. Commented May 1, 2018 at 8:58

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

3 Comments

For the OP, you can turn the JSON object in to an associative array via the default parameter that json_decode takes, just set it to true.
....alternatively you can leave the javascript as-is and read the raw data on the PHP side - stackoverflow.com/questions/8945879/…
@symcbean: Indeed, though you'd want to add contentType: "application/json" (and fix the selector).
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);
}

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.