I want php to return a value to ajax. I'm following W3 schools example but no joy. Here is the javascript/ajax code:
function createReport() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
I have the following call inside an event handler that I know is triggering (other stuff it does is working fine)
createReport();
and later in the body section of the html I have:
<div id="report">Report will be placed here...</div>
If I run test.php by itself, it correctly shows "return this to ajax" so I know that's working. Here is the php code:
<?php
echo 'return this to ajax';
?>
My understanding is that "Report will be placed here..." will be replaced with "return this to ajax". But nothing happens. I don't see any errors listed in the firefox or IE consoles either. Any ideas?
I did not find anything wrong with W3Schools' Ajax example, after testing the code that follows (which was pulled from their Website).
- Possible factors:
- Missing
<script></script>
tags - Make sure you have JS enabled.
- Make sure your browser supports it.
- You may have forgotten to change the button's call to the proper function.
Working and tested code using FF 26.0 and IE version 7
Pulled from
W3 Schools Website (example)
and slightly modified to prove this works.
Result when clicking on the
Change Content
button:return this to ajax
- as per your PHP code.<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="report"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
PHP used: (test.php)
<?php
echo 'return this to ajax';
?>
- Other possible factors:
- If on a
local
machine, your server doesn't support PHP or is not parsing PHP properly, or is either not installed or configured properly. - If on a hosted service, make sure PHP is available for you to use.
- Files are not in the same folder as executed from.
- If on a
0 comments:
Post a Comment