Pass javascript array to server using jquery .post on submit and then print array in PHP?

StackOverflow https://stackoverflow.com/questions/8101555

  •  27-02-2021
  •  | 
  •  

Question

HTML:

<form id="continue" action="summary.php" method="post">
<input type="submit" value="Continue" >
</form>

JS/JQuery

$('#continue').submit(function(){
    var data = ["jon", "steve"];
    var nameArray = JSON.stringify(data);
    $.post("summary.php", { nameArray: nameArray });
});

PHP

$name = json_decode($_POST["nameArray"]);
print_r($name);

When I click the "Continue" button, I want to be redirected to the summary.php page and list the names. Currently, I get an "Undefined index: nameArray error when the summary.php page is loaded.

I checked firebug and there is no POST. So it looks like nameArray isn't even being posted either. What's the solution?

Était-ce utile?

La solution

This is not the correct way of handling data.

You are posting a page (leaving it) and doing an ajax post within? If you want to stay on the page, you use an ajax post. If you are posting data normally, you use a form post.

If you want to post the name jon or steve as an array you can use the following html

<input type="hidden" name="nameArray[]" value="jon" />
<input type="hidden" name="nameArray[]" value="steve" />

If you want to use ajax, then just dont do it on the submit of a form. You can do it on a submit, but then return false at the end of the function so the page will not be submitted (you will stay on the current page)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top