5

I'm calling a PHP function via Ajax:

var ajax = new XMLHttpRequest();
ajax.open("POST", "file.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

ajax.onreadystatechange = function(){
    if(ajax.readyState == 4 && ajax.status == 200){
        var returnVal = JSON.parse(ajax.responseText);

        // do stuff here //
    }
}   
ajax.send('term=' + javaScriptArray);

All is fine, and it works a treat when sending a single value, but falls short when I try and POST an array.

In my PHP function, I am checking to see if the POST variable is an array:

is_array($_POST['term']);

but it always returns false.

Echoing the value prints something like:

value1,value2,value3

but as a single string, not as an array.

This SO thread has an answer that does not send as an array, but rather as multiple different variables, and uses GET:

ajax.open("GET","myserver.com/myfunction.php?var1=1&var2=2&var3=3",true);

The data I am sending is always variable in number of items, and so sending as an array is the best option for me. A simple is_array() in the PHP is a lot simpler for what I am doing.

I've looked at setting multiple variables:

for(var i = 0; i < argument.length; i++){
    postString += 'arg' + i + '=' + argument[i] + '&';
}
ajax.send(postString);

but that still doesn't really get what I'm trying for (again with multiple variables).

I've also tried sending them all with the same variable name:

ajax.send('arg=one&arg=two&arg=three');

but each successive one overwrites its predecessor.

I am not interested in solutions using JQuery. I don't need that whole library, this is the only thing I need.

EDIT 1

I would also like to keep it as POST.

Community
  • 1
  • 1
Birrel
  • 4,754
  • 6
  • 38
  • 74

2 Answers2

7

For an argument to be considered an array it must use [] notation

var postArray = new Array();
for(var i = 0; i < argument.length; i++){
    postArray[i] = 'arg[]=' + encodeURIComponent(argument[i]);
}
ajax.send(postArray.join('&'));
Musa
  • 96,336
  • 17
  • 118
  • 137
2

You will need to make PHP clear, that it is an array you are sending. You usually can do this by adding [], as you would in PHP. So in your example, try this:

ajax.send('arg[]=one&arg[]=two&arg[]=three');
Ascarion
  • 41
  • 4
  • Yes, I noticed that in the PHP it will always be receiving an array now, even if just a single value. Thanks. – Birrel Dec 26 '15 at 05:27