I am using JavaScript Ajax to get response from PHP. In PHP I used echo to return the value for responsiveText
in Ajax however on console.log
I see response as undefined
and therefore further operations are not possible.
AJAX request is:
var xmlhttp = new XMLHttpRequest();
var senddata = "c=" + document.getElementById("image_value").value;
xmlhttp.open("POST", "image_index.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xmlhttp.responsiveText);
}
};
xmlhttp.send(senddata);
PHP file is:
<?php
$im[] = "value1";
$im[] = "value2";
$im[] = "value3";
$i=-1;
if(isset($_POST['i_value'])){
$i=$_POST['i_value'];
}
if($i==-1){
$u="NOTHING";
}
else{
$u=$im[$i];
}
echo "$u";
?>
where im is an array
Don't fret, it's just a simple typo. The response text is responseText
not responsiveText
.
I would also recommend using camel case for your variables, for good programming practice. (e.g. dataToSend
instead of senddata
) In addition, since you used this
inside xmlhttp.onreadystatechange
I would recommend using this
to access its responseText
property. See code sample to see what I mean.
var xmlhttp = new XMLHttpRequest();
var dataToSend = "c=" + document.getElementById("image_value").value;
xmlhttp.open("POST", "image_index.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xmlhttp.send(dataToSend);