Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax and JavaScript, how to POST array *without* using JQuery?

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.

like image 423
Birrel Avatar asked Feb 08 '23 05:02

Birrel


2 Answers

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('&'));
like image 179
Musa Avatar answered Feb 11 '23 00:02

Musa


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');
like image 20
Ascarion Avatar answered Feb 10 '23 23:02

Ascarion