1

We can send (put) single values to send into XMLHttpRequest with Ajax. But how to send "Array" element's values?

EXAMPLE#1 (Ok!)
For this simple value:

<input type="hidden" name="param" value="hello" />

We can simply put the value into XMLHttpRequest object like:

xmlhttp.open("GET","ajax.php?param="+document.getElementById("param").value,true);
xmlhttp.send();

Above method is simple and ok.
But how about to send (put) "Array" values?

EXAMPLE#2 * (Problem with Array Values)

<input type="hidden" name="param[]" value="hello" />
<input type="hidden" name="param[]" value="world" />
...
xmlhttp.open("GET","ajax.php?params="+document.getElementById("param").value,true);


Note: Server side will be with PHP.

1 Answer 1

3

There is no difference (except for a slight change in name). They are just elements with [] in the name attribute as far as HTML, JavaScript and HTTP are concerned. Only PHP is picky about naming conventions for form controls (every other server side language I've encountered deals with expectations of single or multiple values on the server alone, instead of both the server and the client)

The problem is that your initial approach isn't going to work (except in old IE and IE in quirks mode). getElementById gets an element by its ID and your elements only have names.

You can either give the elements IDs or use getElementsByName('param[]') and loop.

Note that you also need to use encodeURIComponent on the data to make it safe for sticking in a URL.

var inputs = document.getElementsByName('param[]');
var query = [];
for (var i = 0; i < inputs.length; i++) {
    var input = inputs[i];
    query.push( encodeURIComponent(input.name) + '=' + encodeURIComponent(input.value) );
}
var url = "ajax.php?" + query.join('&');
Sign up to request clarification or add additional context in comments.

5 Comments

I can't get what you give. Also, what is var input = inputs[1; means ? With single bracket [1 ?
Seems your script has error inside for loop. Coz i can't even alert("aaaa"); after the loop.
Fixed. It has been a long time since I manually constructed a query string.
Ya its now send with the values ?param[]=one&param[]=two&param[]=three. But can't catch from the php. How should i ?
Woah! Thats so great!! I couldn't get before because POST method didn't work and now its ok with GET method. So great!! :)

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.