简体   繁体   中英

Passing an array through jquery ajax to php

I'm trying to turn form inputs into an array (input names as keys and values as values) inside of jquery using serializeArray()... then pass it to a php script via $jquery.ajax.. using the post method.

$(function () {
    $("#xbut").click(function () {
        var values = {};
        $.each($(':input').serializeArray(), function (i, field) {
            values[field.name] = field.value;
        });
        $.ajax({
            type: "POST",
            url: 'ajax/NewClient.php',
            data: {
                clientdata: values
            },
            success: function (data) {
                alert(data);
            }
        });
        return false;
    });
});

i had this working last night... but made some changes and now can't revert. when i use the array conversion for data... i cannot find $_POST['clientdata'] in the NewClient.php.. it just isn't defined. If I change my ajax data into a string... i can find whatever i post.

Any ideas?

I'm pretty sure that

.serializeArray()

should be

.serialize()

$(function() {
    $("#xbut").click(function() {
        var values = {}; 

        $.ajax({
            type: "POST",
            url: 'ajax/NewClient.php',
            data: { clientdata : $(":input").serialize() },
            success: function(data){
                alert(data);
            }
        });
    return false;
    });
});

I've tested your script and it seems to work -

<!DOCTYPE html>
<html lang="en">
    <head>
        <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <script>
        $(function() {
            $("#xbut").click(function() {
                var values = {};
                $.each($(':input').serializeArray(), function(i,field){
                    values[field.name] = field.value; 
                }); 
                $.ajax({
                    type: "POST",
                    url: 'PHPPage3.php',
                    data: { clientdata : values },
                    success: function(data){
                        alert(data);
                    }
                });
            return false;
            });
        });
    </script>
    <body>
    <input type="text" name="tester"/>     
    <input type="button"  value="x" id="xbut"/>   
    </body>
</html>

Then 'PHPPage3.php' is -

<?php
    echo $_POST['clientdata']['tester'];
?>

On clicking the button on the first page the value in the 'tester' field is alerted back.

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