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

What statements should be included in the trigger function when working with AJAX?

There are four steps when creating AJAX.

xhr = new XMLHttpRequest;
xhr.open("GET", "/articles/all");
xhr.send();
xhr.onreadystatechange = function(){ console.log("receive response"};

Assume I want to send the request when I click a button with the id "button" should I only include the send method in the trigger function, like the following

$("#button").click(function(){
  xhr.send();
})

or should I include everything, like this

$("#button").click(function(){
  xhr = new XMLHttpRequest;
  xhr.open("GET", "/articles/all");
  xhr.send();
  xhr.onreadystatechange = function(){ 
    console.log("receive response");
  };
})

1 Answer

Hunter Cassidy
Hunter Cassidy
5,674 Points

You want to create a new XHR for each send.

The instance of XHR will contain information about that request. If you call send multiple times on the same instance it will abort the previous request, so each request should have its own XHR instance.

More info: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#send() http://stackoverflow.com/questions/11502244/reuse-xmlhttprequest-object-or-create-a-new-one http://stackoverflow.com/questions/11178177/when-sending-multiple-xmlhttprequests-only-the-last-request-returns-success