Reputation: 18337
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.
Upvotes: 1
Views: 3918
Reputation: 943650
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('&');
Upvotes: 3