简体   繁体   中英

How do I serialize $_POST data in ajax from a php redirect

I am having users fill in a form on page A, I then redirect to page B sending $_POST data with it. I've seen that I can serialize post data from a form like this $("form").serialize() or this.serialize() but I don't want to retrieve data from a form I need to get it from $_POST. How do I go about serializing $_POST data not from a form that exists on the current page?

When someone submits a form, unless you use Javascript to override the default browser behaviour, they will be taken to page B. You define the "method" and "action" of the form to get the behaviour you want. So, to POST data you'd use method="POST" and to go to pageb.php you'd set action="/pageb.php". Then in pageb.php you can access the POST variables from the form on pagea. Eg

pagea:

<form name="aform" action="/pageb.php" method="POST">
    <input type="text" name="name" />
    <input type="submit" value="Submit" />
</form>

Type your name in, hit submit, get redirected to pageb.php. Then on pageb:

<?php 
    $name = $_POST["name"]; 
    echo $name;
?>

You see the name. Not very exciting though.

You could alternatively use Ajax and the jQuery serialize function to send the form data to pageb.php without leaving pagea.

You could do something like this:

<form id="aform" action="/pageb.php" method="POST" onsubmit="return submitForm(event)">
    <input type="text" name="name" />
    <input type="submit" value="Submit" />
</form>

<script type="text/javascript">

    function submitForm() {
        event.preventDefault();
        $.post('/pageb.php', $("#aform").serialize(), function(response) {
             // Do something with the response
        });
    };

</script>

That's pretty basic but it stops the form behaving normally, serializes the form and sends it to pageb. pageb.php would have to output text of some kind, plain or JSON perhaps depending on what you want to achieve.

I found a solution to this in case anyone else ever wonders how to do this. var post_info = []; creates an array to hold all of the $_POST variables. This is what takes all the post variables and puts them into a json array for ajax post_info = <?php echo json_encode($_POST); ?>; post_info = <?php echo json_encode($_POST); ?>; . And the ajax looks like normal.

            "ajax": {
                "url": "ajax/test.php",
                "type": "POST",
                "data": {post_info: post_info}
            },

On the php side I didn't need to json_decode because ajax sends this as a $_POST variable. Except it is now a multidimensional array so accessing variables looks like this $_POST['post']['item'] . And there you go. I've never answered my own question before.

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