1

I'm using $.ajax to send the values of a form to a PHP script.

The form input fields are read like arrays by PHP, but I don't know how to do the same with javascript and jQuery, and send them in such a way that PHP is able to read them like arrays.

For example a input named foo[bar] in PHP you get it as $_POST['foo']['bar']

Currently I'm sending this data like

data:{
   foo_bar: $('form').find('#foo_bar').val(),
   foo_xxx: $('form').find('#foo_xx').val()
},

and manually assembling the array in the PHP script.

But it's starting to take a lot of lines of code. Could I somehow automate this, and send all the form input as an multidimensional array to PHP?

2
  • I'm not sure I can visualize what you're trying to do. More code, please? Commented Jun 22, 2012 at 15:06
  • Form fields are usually in the form of key->value pairs... so what do you mean by multi-dimensional? in what way is it going to be multi-dimensional? Commented Jun 22, 2012 at 15:09

2 Answers 2

5

You could use $.serialize();

data: {
  d: $('form').serialize()
}

Check for more information here: http://api.jquery.com/serialize/

It will send back a string field=value&field2=value& and you could use parse_str to handle it

parse_str sample:

$foo = "t[]=1&t[]=2&b=3";
parse_str($foo, $bar);
var_dump($bar);

Results to:

array(2) {
  ["t"]=>
  array(2) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
  }
  ["b"]=>
  string(1) "3"
}
Sign up to request clarification or add additional context in comments.

3 Comments

What do you mean by one level?
well the strings looks like it doesn't support more levels than one but I was looking at implode/explode. Can parse_str decode it as multidim. array?
you are right, parse_str works differently than explode. thanks :P
4

You do not have to do any thing special. Declare your field names exactly the way you want PHP to interpret them:

<form>
<input name="foo[bar]" id="foo_bar">
<input name="foo[xxx]" id="foo_xxx">
<input name="a[]" id="a_0">
<input name="a[]" id="a_1">
<input name="b[0][1][2]" id="b_0_1_2">
</form>

jQuery.serialize will url-encode the form fields just the way you expect:

data: $("form").serialize()
// foo%5Bbar%5D=&foo%5Bxxx%5D=&a%5B%5D=&a%5B%5D=&b%5B0%5D%5B1%5D%5B2%5D=

When this is passed as a query string to a PHP page:

/phpinfo.php?foo%5Bbar%5D=&foo%5Bxxx%5D=&a%5B%5D=&a%5B%5D=&b%5B0%5D%5B1%5D%5B2%5D=

You get:

$_GET["foo"] = Array
(
    [bar] => 
    [xxx] => 
)
$_GET["a"] = Array
(
    [0] => 
    [1] => 
)
$_GET["b"] = Array
(
    [0] => Array
        (
            [1] => Array
                (
                    [2] => 
                )
        )
)

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.