I've got this form, which generates an array as output, and I want to send that via AJAX to a PHP page. The form is build up like this: [using a lot more entries]
<input type="hidden" name="reisdata[Van]" value="'.$reisdata["Van"].'">
<input type="hidden" name="reisdata[Naar]" value="'.$reisdata["Naar"].'">
and the php page needs to recieve the data as an array.
Now, someone showed me this piece of code, to pass an array in AJAX via POST, but I still don't know how to read the array in javascript.
So: How can I read an array from a form, in AJAX / Javascript? Do I just read it by typing: document.formname.reisdata ?
This is my AJAX code:
// Algemene functie om een xmlHttp object te maken. Via dit object kunnen we later Ajax calls plaatsen
function GetXmlHttpObjectReisData() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) { // Internet Explorer
try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
function CallAjaxReisDataFunction(serverScript,arguments)
{
var xmlHttp = new GetXmlHttpObjectReisData(); // Functie welke wordt uitgevoerd als de call naar de server klaar is State 4)
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
handleReisDataResult(xmlHttp.responseText);
}
}
// Ajax call (Request naar de server met eventuele parameters (arguments))
xmlHttp.open("POST", serverScript, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", arguments.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(arguments);
}
function callReisDataServer(serverScript,van,naar)
{
CallAjaxReisDataFunction(serverScript,"?&reisdata=" + reisdata);
}
function handleReisDataResult(responseText)
{
document.getElementById('reis').innerHTML = responseText;
}
This is the code someone ( @mephisto123 ) gave me before, but this works with a predefined javascript array:
var postdata = {"provincie":"123","reisdata":{"Overstap":"234","Van":"345"}};
var post = "";
var url = "data-reis-refresh.php";
var key, subkey;
for (key in postdata) {
if (typeof(postdata[key]) == object) {
foreach (subkey in postdata[key]) {
if (post != "") post += "&";
post += key + "%5B" + subkey + "%5D=" + postdata[key][subkey];
}
}
else post += key + "=" + postdata[key];
}
req.open("POST", url, true);
req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", post.length);
req.setRequestHeader("Connection", "close");
req.send(post);