Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics AJAX Concepts A Simple AJAX Example

Pablo Calvo
Pablo Calvo
13,044 Points

Local Webserver setup for this video not working

Hello,...im trying to follow along the video with my own webserver setup... followed the steps in the teacher's note video.... BUT, I can't seem to make it work with my file here, I got all the programming the same and console will give me this error:

Access to XMLHttpRequest at 'http://localhost/index.php' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

the following statement: xhr.open('GET', 'http://localhost/index.php')

I've tried (localhost), and several other combinations, I guess what I need is the correct path to put on the xhr.open, but I cant seem to nail it... thanks for any advise.

Here is my html file

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- <link href='//fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'> --> <link rel="stylesheet" href="css/main.css"> <title>AJAX with JavaScript</title> <script> var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (xhr.readystate === 4){ document.getElementById('ajax').innerHTML = xhr.responseText; } }; xhr.open('GET', 'http://localhost/index.php'); xhr.send(); </script> </head> <body> <div class="grid-container centered"> <div class="grid-100"> <div class="contained"> <div class="grid-100"> <div class="heading"> <h1>Bring on the AJAX</h1> </div> <div id="ajax">

      </div>
    </div>
  </div>
</div>

</div> </body> </html>

1 Answer

Justin Smith
Justin Smith
9,843 Points

The minified javascript you posted is a little hard to read, but I suspect the problem might be with your 'xhr.readystate ===4' bit. The method uses camel casing and so the second 's' should be uppercase like this: 'xhr.readyState === 4'. Though I have no idea why xhr.onreadystatechange doesn't use camel casing.