简体   繁体   中英

Simple AJAX example for PHP not working

This is my first question regarding PHP so please bear with me. I've been following tutorials from phpacademy.org.

I'm stuck on one tutorial where an intro to AJAX is given. I typed in the exact code as the tutor, still its not working on my end.

I searched alot for it but it didnt help one bit. Could anybody help me out here? Here's my code:

<html>
<head>
<script type="text/javascript">
function load(){

if(window.XMLHttpRequest)
    xmlhttp=new XMLHttpRequest();
else
    xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');

xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementsById('adiv').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'AJAX.inc.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="adiv"></div>
<input type="submit" value="Submit" onclick="load();">
</body>
</html>

And here's the AJAX.inc.php file:

<?php
echo 'Hello AJAX';
?>

However another example from w3school.com is working.

Possible duplicate: AJAX not working with XAMPP or is it just impossible

But this question isn't properly answered (or I dont understand it). Would someone please clarify it?

There is no document.getElementsById method.

document.getElementsById('adiv').innerHTML=xmlhttp.responseText;

Should be

document.getElementById('adiv').innerHTML=xmlhttp.responseText;
<html>
<head>
<script type="text/javascript">
function load(){

if(window.XMLHttpRequest)
    {
    xmlhttp=new XMLHttpRequest();
    }
else
    {
    xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
    }
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementById('adiv').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajax_php.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="adiv"></div>
<input type="submit" value="Submit" onclick="load();">
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM