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.

1
  • JSON.stringify works without jquery Commented Dec 26, 2015 at 5:22

2 Answers 2

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('&'));
Sign up to request clarification or add additional context in comments.

2 Comments

That'll do it. I didn't know about the [] syntax for posting an array, Much thanks!
I'd +1 again if I could for the .join() - I've never seen that before.
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');

1 Comment

Yes, I noticed that in the PHP it will always be receiving an array now, even if just a single value. Thanks.

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.