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/