简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM