Uros Bojanic Uros Bojanic - 4 months ago 19
HTML Question

ajax simple code not working

I know I might just be missing a simple thing that's right under my nose, or may not understand ajax at all... but I have a problem - this simple peace of code isn't working, but it's from w3schools and it's the simplest example of ajax working.
Can someone help me, please?



<!DOCTYPE html>
<html>
<body>

<div id="demo"><h2>Let AJAX change this text</h2></div>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>

</body>
</html>





Here's the "ajax_info.txt" file:


text changed.

Answer

If you're not running the code using a server (i.e MAMP or WAMP for local) you'll get the following error:

index.html:18 XMLHttpRequest cannot load ajax_info.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Also a file called ajax_info.txt needs to exist in the same directory as this html file. Otherwise this javascript AJAX call:

xhttp.send(); 

Will return an error: /ajax_info.txt 404 (Not Found)