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) Programming AJAX Parsing JSON Data

Claudio Gomes
Claudio Gomes
8,872 Points

Can I standardize AJAX calls in a general function?

The code below doesn't work and returns undefined instead of an array object. Any ideas why this is happening. My guess is because the function exits before the response comes. If so, is there a way I could circumvent this (I have real use for this - I just want to understand).

   function callAjax(fileName) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      return xhr.responseText;   
    }
  };
  xhr.open('GET',fileName);
  xhr.send();
  }
  console.log(callAjax('data/employees.json'));

Context

@ https://teamtreehouse.com/library/ajax-basics/programming-ajax/parsing-json-data I was presented the following code which returns an array to the console.

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      var employees = JSON.parse(xhr.responseText);
      console.log(employees);
    }
  };
  xhr.open('GET','data/employees.json');
  xhr.send();

I thought I could standartize this code as per further above so i dont have to rewrite it everytime I need a GET AJAX as mentioned, this always returns undefine

Tommaso Poletti
Tommaso Poletti
5,205 Points

if you continue with the course you will learn to do the same thing with the jquery .

And you shall write all that code into a single line

1 Answer

Kristian Gausel
Kristian Gausel
14,661 Points
   function callAjax(fileName, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      callback(xhr.responseText);   
    }
  };
  xhr.open('GET',fileName);
  xhr.send();
  }
  callAjax('data/employees.json', console.log);

Should work (I haven't tested it) But the idea in javascript is to use callbacks with listeners. But like the other guy here said. Just use jQuery ;)