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 (retiring) AJAX Concepts A Simple AJAX Example

Fenia Vasileiou
Fenia Vasileiou
7,349 Points

Problem with ajax code, can not get data from my local web server's html file "sidebar.html"

I go throught the video instructions and set up a local web server "XAMPP". On file C:\xampp\htdocs resides the "sidebar.html". Loading the index.html i get the above error:

"XMLHttpRequest cannot load http://localhost:8080/sidebar.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."

<script>
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function () {
    if(xhr.readyState===4){
      document.getElementById('ajax').innerHTML = xhr.responseText;
    }
  };
xhr.open('GET', url='http://localhost:8080/sidebar.html');
 xhr.send();
</script>

I am a beginner with Ajax and this is my first try, any help?

3 Answers

Mustafa Başaran
Mustafa Başaran
28,046 Points

Hello Fenia, Your code is fine except the following line:

xhr.open('GET', url='http://localhost:8080/sidebar.html');

So changing that to

xhr.open('GET', 'sidebar.html');

should work.

Please note that url= is redundant. Moreover, you are making an AJAX request to a page on the same folder as index.html and server...
I hope that this helps. Best regards, Mustafa

How are you getting on with this?

Fenia Vasileiou
Fenia Vasileiou
7,349 Points

Thank you for your answer, it worked!!