December 31, 20196 yr Hello friends, I am new to ajax and was follwoing a youtube video but some how this code not working on wamp here is the code index.php <!DOCTYPE html> <html lang="en"> <head> <script> function load(){ if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4 && xmlhhtp.readyState == 200){ document.getElementById("adiv").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET","include.inc.php",true); xmlhttp.send(); } } </script> </head> <body> <input type="submit" onclick="load()"> <div id="adiv"></div> </body> </html> and include.inc.php <?php echo "Hello!"; ?> both the files in same folder so there is no issue with filepath me testing this on wamp server any help will be highly appreciated..thanks
December 31, 20196 yr In your first block you test for window.XMLHttpRequest On my chrome this is set but your code does nothing unless its not set. Simply moving the end else bracket gets code I think you need. function load(){ if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4 && xmlhhtp.readyState == 200){ document.getElementById("adiv").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET","include.inc.php",true); xmlhttp.send(); } Running the function then correctly gets a 404 (For the the WDF server) load() undefined VM145:13 GET https://www.webdesignerforum.co.uk/topic/include.inc.php 404 load @ VM145:13 (anonymous) @ VM163:1 VM145:8 Uncaught ReferenceError: xmlhhtp is not defined at XMLHttpRequest.xmlhttp.onreadystatechange (<anonymous>:8:35) xmlhttp.onreadystatechange @ VM145:8 XMLHttpRequest.send (async) load @ VM145:13 (anonymous) @ VM163:1 So you just needed to actually do somthing in browsers where window.XMLHttpRequest is set.
January 2, 20206 yr You typically don't see people interfacing with XMLHttpRequest like this anymore because it's a terrible API to work with. You might find it easier using a library like Axios or using the built-in fetch API in browsers. Both of these return a Promise Object that you can use to transform returned data, or catch any errors. It should make debugging easier than manually having to check for all possible error cases and handing the errors yourself.
Create an account or sign in to comment