I have a JS-PHP script where the JS sends information to the PHP script and then displays the PHP response in my HTML page. The script works properly if I display the responseText in one area. When I try to parse the responseText so I can display it in different areas, the script doesn't work. Where am I going wrong?
End of my PHP Script:
...
$expert = $obj;
$pro = $obj1;
$superview = $obj2;
echo json_encode(array(first=>$expert,second=>$pro,third=>$superview));
?>
PHP response:
{"first":1860,"second":1100,"third":340}
JavaScript:
// this calls the php script with the data we have collected from the geolocation lookup
function GEOajax(url) {
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4 && xmlhttp.status==200) {
var response = JSON.parse(xmlhttp.responseText);
document.getElementById("geo").innerHTML='' + response.first;
document.getElementById("geo1").innerHTML='' + response.second;
document.getElementById("geo2").innerHTML='' + response.third;
}
}
HTML:
<div id="geo" ></div>
<div id="geo1" ></div>
<div id="geo2" ></div>
However, if I do not parse the text in JS, but just use the entire responseText, then the script works and displays the responseText in my HTML properly.
JavaScript - no parsing:
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4) {
var response1 = xmlHttp.responseText;
document.getElementById("geo").innerHTML = '' + response1;
}
}
How can I parse the PHP response so I can display different variables in different areas in HTML?