manuka_m manuka_m - 4 months ago 19
Javascript Question

Send javascript arrays via ajax without using jquery

i have a javascript array with values like "correct", "wrong".
I want to send this array to my php file using ajax. But im not familiar with how.
This is what i have tried so far..and i would like to do this without jquery.

var hold=[];
for(t = 0;t <= 10; t++){
answers_Arr = document.getElementsByName("question"+t);
for (k = 0; k < answers_Arr.length; k++){
if(answers_Arr[k].checked){
hold[t] = answers_Arr[k].value;
//document.getElementById("test"+t).innerHTML = "Value: "+ hold[t];
break;
}else{
hold[t] = "no";
continue;

}
}
}
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test1").innerHTML= xmlhttp.responseText;
}
}

xmlhttp.open("GET","result.php?res="+hold[],true);
xmlhttp.send();

}

Answer

Here is an example of sending the json string with POST through AJAX:

var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    //
}

xmlhttp.open("POST","result.php",true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonString);

Avoid sending json strings with GET method because if the request string gets too long, the browser will throw you an error.

Now in your php script you will have all the data in $_POST