Not sure where AJAX data is coming in

Here is the part I’m having trouble understanding. Where/how are we getting the data from the server?

I understand the syntax to send a jQuery get request.

I understand how to use the data once I get it.

What I don’t understand, i guess is where do I define the variable or object in where the data is coming into.

Here is an example to help:

$getJSON(url, data, success);
$(whereToPutTheInfo).text(???);

As the name implies AJAX allows to make asynchronous calls to the server and by that leaving the JS execution available for other tasks. When the server returns the data to the client, the AJAX engine is the part that handles the response.

That is , when you use $.getJSON, $.ajax or simple XMLHttpRequest you send an AJAX request to the server and you also provide a callback function which should be executed when the response come back to the client.

You must know that when you call $.getJSON the response doesn’t come back and handled immediately and therefore you must specify a callback to return the data to the correct context you want to use it (in your case, to set the text of a DOM element).

One method to do it correctly is using promise. A promise provides intuitive way to deal with the completion of asynchronous tasks. When you call $.ajax for example, it returns a promise which has methods which internally get called when the asynchronous call is completed.

For example:

 var promise = $.ajax({
     url: "/ServerResource.txt"
 });
            
 promise.done(successFunction);
 promise.fail(errorFunction);
 promise.always(alwaysFunction);

The promise then returned by $.ajax and the methods done, fail and always will be called internally depends on the ajax response. If the response is done without any errors then the methods done and always will be called, otherwise the methods fail and always will be called.

In your case you can take for your advatnage the $.getJSON API and handle the response according to the $.getJSON promise interface.

Here is an example taken from jQuery API pages:

 var jqxhr = $.getJSON( "example.json", function() {
   console.log( "success" );
 })
   .done(function() {
     console.log( "second success" );
   })
   .fail(function() {
     console.log( "error" );
   })
   .always(function() {
     console.log( "complete" );
   });

As you can see from the snippet code above, $.getJSON promise API supports the success callback which will be called when the response come back and completed. This is exactly the part where you can put your piece of code with the response (information you wanted) available.

Finally you should also understand that you don’t define a variable in where the data is coming into but instead you supply a callback function which the data is provided into via the parameter. This parameter can be used in the success callback function.

So in your case the code will look as following:

 var jqxhr = $.getJSON( "A JSON FILE", { param: 'value' }, function(res) {
   $(DOM_ELEMENT).text(res[SOME_ATTRIBUTE]);
 })

Make sure to handle the fail method as necessary and also make sure to send parameters to the server if needed.

Related links:
http://api.jquery.com/jquery.getjson/

1 Like

Thanks, I think I have an idea of what’s going on now. However, I’m still having trouble getting it to work. Any ideas on where I’m going wrong?

This video series is simple, yet adequately describes the basics of Asyncronous code, AJAX, XMLHTTP requests, etc. It will take about an hour, I suggest you watch it all:
http://www.thenetninja.co.uk/courses/asynchronous-javascript-tutorial


For your codepen, your code looks correct, the link in your html variable is bad. Check out the link in a new tab, remember that your browser is great at displaying JSON code, especially if you add a code formatting plugin.
https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en

You will see it says:

Origin: header is required

However if you run it without the CORS proxy, it works (altough not on codepen):
http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en

To get it to work on codepen, I suggest using JSONP over JSON:

var html='http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=?&lang=en';

Is there anything else I need to do to use jsonp? It’s still doesn’t seem to be working on codepen. I will also try using just a text editor like brackets and see how that works.

Works absolutely fine if it’s not run in codepen. I wrote the script up in coffeecup html editor and tested it, works great.

I figured out why it wasn’t working in codepen. There is an issue if the api is http and codepen is https or vice-versa.

Everything seems to be working absolutely fine now. Thanks everyone for the help.

Correct. API’s are usually meant to be run on the server not the client, and you will run into a lot of similar problems if you use codepen. I build almost all my sites locally in my command prompt now.

Congrats on getting it all worked out! :smiley: