Warwick Warwick - 6 months ago 12
jQuery Question

How to send array to PHP using jQuery $.post()

I want to send data to a PHP page using jQuery's $.post(), with a

$_POST
result that will look like this:

Array
(
[text] => Some String
[numbers] => Array
(
[0] => 9
[1] => 4
)

)


The information that becomes the
numbers
array is dynamically generated, so I have no idea how many elements it will consist of. So, I have to gather this info into a JavaScript array.

I have this jQuery code so far:

$.post("http://some.url/page.php",
{
text: $("#string").val(),
numbers: $("#container input").val() //This is obviously wrong!
}).done(function (result)
{
$("#result").html(result);
});


How do I get the values from the
input
elements in
#container
into an array at the
numbers:
point, to get an array within the
$_POST
array?

EDIT: HTML looks something like this:

<input type="text" name="text" id="text">
<div id="container">
<label id="9"><input type="hidden" value="9">You added no. 9!</label>
<label id="4"><input type="hidden" value="4">You added no. 4!</label>
<!-- These inputs are dynamically added with a whole other function -->
</div>

Answer

Your html inputs must have a names like:

  • name="text" -> for "name" input

  • name="numbers[]" -> for two "numbers" inputs

So html:

<form class="form">
    <input type="text" name="text" id="text">
    <div id="container">
        <label id="9"><input  name="numbers[]" type="hidden" value="9">You added no. 9!</label>
        <label id="4"><input  name="numbers[]" type="hidden" value="4">You added no. 4!</label>
        <!-- These inputs are dynamically added with a whole other function -->
    </div>
<form>

When try to serialize your form inputs:

$.post("http://some.url/page.php",
{
  data: $('.form').serialize(),
}).done(function (result)
{
    $("#result").html(result);
});
Comments