How to pass array to php using $.post method

Cicero

Expert Member
Joined
Jul 20, 2010
Messages
2,286
Reaction score
14
Location
Coastal
I have a multiple select box, and I want to pass the selected contents to a php script to use in a db lookup. But I just can't get it to pass an array at all.

I'm testing now with trying to pass a direct array (not via the select), myArr, and it still only passes one of the values in the array:
So using the post method here to getseldb.php, passing in selectHandle and myArr, and getting back dataout. Then I just print what it gets back to the console.
Code:
var myArr= ["test1", "test2"];
          
$.post('getseldb.php', {select: selectHandle, data_in: myArr}, function(dataout) {
        
console.log(dataout);
});

My php code just looks like this to echo the input data:
Code:
print_r($_POST);

The console spits out this:
Code:
Array
(
    [select] => selectID
    [data_in] => test2
)
 
dont quote me on this, because I dont know PHP, but I dont think the default conversion service knows how to handle this


You could probably achieve this using `JSON.stringify` on the client side, and `json_decode` on the server side



if you want to do this in a form, instead of

PHP:
<form action="dog.php" method="POST">
      <input name="firstname" />
      <input name="firstname" />
      <button type="submit">Submit</button>
    </form>

do

PHP:
<form action="dog.php" method="POST">
      <input name="firstname[]" />
      <input name="firstname[]" />
      <button type="submit">Submit</button>
    </form>

then it will be an array on the PHP side
 
Last edited:
Yeah, so adding brackets worked.

Now I just have to parse it on the other side, all the different syntax's really make me frustrated.
 
if memory serves...

Code:
foreach ($_POST['firstname'] as $key => $firstname)
{
//your code
}

EDIT: add <input name="firstname[]" multiple /> to be safe
 
Multiple is only defined in the HTML5 spec as an attribute to use on inputs of type file and email.
It has nothing to do with manipulating how data is assembled or posted.
 
Code:
		var myArr = {};
		myArr[0]="A"; 
		myArr[1]="B";
		$.ajax({
...
			data: {'myArr':myArr},
...

then

Code:
foreach ($_POST['myArr'] as $k=>$v)
	//$k=0,1,...
	//$v=A,B,...
 
Top
Sign up to the MyBroadband newsletter
X