Uros Bojanic Uros Bojanic - 1 year ago 94
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>

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

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

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);


Here's the "ajax_info.txt" file:

text changed.

Answer Source

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:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download