So I've got some code that retrieves a series of objects from an API. When I try to store them in a global variable, it doesn't seem to do anything. Here's the code:
var current_corpus = {};
function page_init() {
$.getJSON("http://resource1.com", function(data) {
populate_collections(data);
populate_citations(data);
});
}
function populate_collections(collections) {
$.each(collections, function (i, item) {
current_corpus[item] = [];
});
}
function populate_citations(collections) {
$.each(collections, function (index, collection) {
$.getJSON("http://resource2.com/" + collection.collection_id, function(data) {
current_corpus[collection] = data;
console.log(current_corpus);
});
});
}
When this finishes, current_corpus is completely empty. Logging these items verifies that they're being returned from the resources I'm posting to. I think there's just something about the asynchronous nature of these calls that I'm missing.
The line
current_corpus[item] = [];
is superfluous I think as the line
current_corpus[collection] = data;
should do the same thing while also tying data to the key object. Either way at the end of these functions running trying to access current_corpus via the console just gives me back an empty object.
Resources for dealing with AJAX stuff like this would be appreciated as well.
It all depends on what you want to do when the ajax requests complete. The A in ajax stands for Asynchronous meaning that such requests are non-blocking -- i.e. they will run in the background as control moves to the next line. Which explains why you're seeing an empty object right after the functions that invoke the ajax requests.
You can confirm that your code is working fine or you can do something once all the requests complete by using the following code snippet:
$(function() {
$(document).on('ajaxStop', function() {
console.log( current_corpus );
//do something with the now fully constructed object
});
});
Related
For as simple as this should be, I have no idea what I am doing wrong. I'm attempting to fetch a local text file and store it in a variable, but regardless of the method (fetch api, $.get and ajax) I use, I always get undefined.
$(document).ready(function() {
var fileConfiguration;
$.get( "Configuration.h", function( data ) {
fileConfiguration = data;
});
document.getElementById("demo").innerHTML = fileConfiguration;
});
The data variable is properly fetched, I can use alert or console.log and see the contents correctly. When I assigned it to a variable though, it's undefined. I imagine this has something to do with it being an asynchronous callback, but can't figure out the problem.
As you and #charlietfl have pointed out the AJAX request is asynchronous which means that the last statement in your code is executed before there's a response, hence fileConfiguration is still undefined.
Therefore the best place to do the assignment is inside the callback like so:
$(document).ready(function() {
$.get( "Configuration.h", function( data ) {
document.getElementById("demo").innerHTML = data;
});
});
I've tried Googling this but could not reslove it. It may seem like a really simple issue to others but I'm baffled by it. I have the below code in which I get undefined for the first alert but I still get the correct values in the 2nd alert. BUT if I comment out the first alert (just the line with alert) then the 2nd alert output becomes undefined. Can any one explain why this is and how I may output the 2nd alert correctly without the first one, any Help is greatly appreciated.
function getDetails(ID){
var qArray = [];
$.get('get_Question', {"Id":ID}, function(){})
.success(function(data){
var json = $.parseJSON(data);
qArray.push(json.value1);
qArray.push(json.value2);
});
//First Alert
alert("-> "+qArray[0]);
return qArray;
}
This is the 2nd alert which calls the above method:
var myArray = getDetails(4);
alert("myArray [0]: "+myArray[0]);
You can't return a value, the $.get() call is asynchronous.
You need to defer any operations on qArray until the AJAX call has completed, i.e. inside the callback.
Better yet, use deferred callbacks:
function getDetails(ID) {
return $.get('get_Question', {"Id":ID})
.pipe(function(json) {
return [json.value1, json.value2];
});
}
The .pipe deferred function creates a new promise which will ultimately return the desired array, but only once the AJAX call has completed.
You would then use this like this:
getDetails(ID).done(function(qArray) {
alert("-> " + qArray[0]);
});
Note that $.get() doesn't directly support error callbacks, but with deferred objects you can get access to them:
getDetails(ID).done(function(qArray) {
alert("-> " + qArray[0]);
}).fail(function(jqXHR, textStatus, errorThrown)) {
alert("The AJAX request failed:" + errorThrown);
});
Without this you'd need to build the error handling directly into the getDetails() function and then require some mechanism to tell the rest of the application logic about the error.
NB I've assumed that you don't really need to call JSON.parse() manually - if your web server returns the right Content-Type header then jQuery will do that for you automatically.
Ajax calls happens asynchroniusly, meaning you can't wait for the call to return and get the value. The way to do it is to employ a callback. Your example will become something similar to this:
function getDetails(ID, callback){
$.get('get_Question', {"Id":ID}, function(){})
.success(function(data){
var qArray = [];
var json = $.parseJSON(data);
qArray.push(json.value1);
qArray.push(json.value2);
callback(qArray)
});
}
Calling it will change a bit:
getDetails(4, function (myArray) {
alert("myArray [0]: "+myArray[0]);
});
The First Alert is called before the ajax call is finished, so the variable is still undefined.
This is because the $.get() is done asynchronously. There is no option for $.get() to pass parameter for async calls, so you should use $.ajax() instead and pass a param async: false
The $.get call creates a new asynchronous request for the resource in question.
When you call the first alert it is undefined because the request hasn't been completed yet. Also since you are forced to pause on the alert the request has time to be completed in the background. Enough time for it to be available by the second alert.
The same thing happens when you comment out the first alert. This time the second alert is called before the request is completed and the value is undefined.
You need to either make your requests synchronous or consider continuing execution after receiving the response by using a callback function within the success callback function you have already defined in $.get.
As several others have said, ajax-request are asynchronous. You could however set the async property to false to get a synchronous request.
Example:
function getDetails(ID) {
var result = $.ajax('get_Question', {
async : false,
data : { 'Id' : ID }
});
// do something with the result
return result;
}
I myself would have use a callback function instead beacuse async:false is bad practice and is also deprecated.
You'll need to rewrite $.get to use $.ajax and specify async: false
AJAX is asynchronous: you can't tell when the request will complete. This usually means you need to pass callback methods that will be called with the result of the request when it completes. In your case this would look something like:
function getDetails(ID, callbackFunc){
$.get('get_Question', {"Id":ID}, function(){})
.success(function(data){
var qArray = [];
var json = $.parseJSON(data);
qArray.push(json.value1);
qArray.push(json.value2);
callbackFunc(qarray);
});
}
getDetails(4, function(qArray) {
alert("myArray [0]: "+qArray[0]);
};
Struggling to load json from file (myData.json) on URL into an object so I can access property values.
-- The data loads immediately, I need it a lot in the app.
-- I'm going to access the data throughout the app, not just as part of one function that happens immediately after the data loads.
-- I've ensured the data in my file is properly formatted json.
Following the example on the jquery API, shouldn't I be able to do something simple like:
alert(jqxhr.myProperty);
and get the value? What step am I missing here? I've tried running eval and a variety of things like
var myObj=JSON.parse(jqxhr);
to no avail.
Please....thank you.
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON("example.json", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
I think you are making it too complicated :)
var JSON;
$.getJSON('example.json', function(response){
JSON = response;
alert(JSON.property);
})
//feel free to use chained handlers, or even make custom events out of them!
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
the getJSON function automatically converts your response into a proper JSON object. No need to parse.
You mentioned that you are using this data all over the place, so you will have to wait for the ajax call to complete before the data is accesible. That means either wrapping your entire application in the getJSON callback. Or using a custom event to determine like so:
var JSON;
$(window).on('JSONready', function(){
alert(JSON.property);
});
$.getJSON('example.json', function(response){
JSON = response;
$(window).trigger('JSONready');
});
$('#elem').on('click', function(){
//event likely to take place after ajax call has transpired
//it would still be better to assign this listener in a callback,
//but you can get away with not doing it, if you put in a catch
if(JSON){
alert(JSON.property);
}
});
EDIT
After a quick live debug, the real reason for the data being unavailable was this: javascript that consumes JSON was located in a file include the page document NORTH of inline javascript performing the call. As a result JSON was not a global variable, and scope prevented its usage. If you truly need a variable to be global so it can be used with inline JS as well as any and all included js files, you may do so like this:
(function(){
var limitedScopeVariable = 25;
window.globalScopeVariable = 30;
})();
$(function(){
alert(globalScopeVariable); //works!
alert(limitedScopeVariable); //fails!
});
EDIT 2
As of jQuery 3.0, callback functions are different: The
jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods
are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead
from the comments #mario-lurig
the json data is passed to the callback function of $.getJSON.
So this would work:
var jqxhr;
$.getJSON("example.json", function(data) {
jqxhr = data;
});
// alert(jqxhr.property);
// caution: this won't work immediately on load, since the ajax call runs asynchronously and hasn't finished at that time
// it should be available at a later time, like a click event
$('a#something').click(function(){
if(jqxhr){
alert(jqxhr.property);
}else{
alert('getJSON not yet complete or failed');
}
});
I think this would be what you are looking for, you are trying to access the data returned from your call not the caller object itself. In your example, jqxhr is the object that handles the JSON call not the data. So,
$.getJSON("example.json", function(data) {
yourDATA = data;
})
//Use your data here
alert(yourDATA.aProperty);
The very first example on this page is similar to what I explained.
I have the following code which is included in a keypress function:
$.getJSON('dimensions.json', function(data) {
$.each(data, function(index) {
$('#div1').append(index);
});
});
I'm trying to first get the JSON string, save it in a variable and then run the each(). I want to basically separate the each() to be unlinked to the getJSON() function because I don't want it to fetch the json file for every keypress.
I've tried this, but it didn't work:
var JSONstr = $.getJSON('dimensions.json');
$.each(JSONstr, function(index) {
$('#div1').append(index);
});
In your first example, you do $.each in the callback. The callback is executed by some other callback after there result is received, while $.getJSON returns immediately without waiting for the result (since there is no blocking in JavaScript by design).
Therefore the code in your second example can never work: the $.each begins before any result is received from the web server, probably even before the request is sent. Whatever the return value of $.getJSON is, it can't, by the design of JavaScript, be the result of AJAX request.
UPD: Saw your comment, now I understand what you wanted to do. Here's a simple example of how to do this:
function ActualHandler(data) {
$.each(data, function(index) {
$('#div1').append(index);
});
}
function KeypressHandler() {
if (window.my_data) { // If we have the data saved, work with it
ActualHandler(window.my_data);
}
else { // Otherwise, send the request, wait for the answer, then do something
$.getJSON('dimensions.json', function(data) {
window.my_data = data; // Save the data
ActualHandler(data); // And *then* work on it
});
}
}
Here, the ActualHandler is not launched before the data is received, and once that happens, all subsequent clicks will be handled immediately.
The downside in this particular case is that if user clicks again while the first request is running, one more will be sent. But to fix that you would need to maintain some queue, which is kind of out of scope here.
You fell into the asynchronous trap. Your $.each() function doesn't wait for your $.getJSON() call to get the data. You can get around this by using the good 'ol $.ajax() function. Like this:
function processJSON(data) {
$.each(data, function(index) {
$('#div1').append(index);
});
}
$.ajax({
url: 'dimensions.json',
dataType: 'json',
async: false,
success: processJSON(data)
});
Alright, I know questions like this have probably been asked dozens of times, but I can't seem to find a working solution for my project. Recently, while using jQuery for a lot of AJAX calls, I've found myself in a form of callback hell. Whether or not jQuery is too powerful for this project is beyond the scope of this question. So basically here's some code that shows what's going on:
function check_form(table)
{
var file = "/models/"+table+".json";
var errs = {};
var xhr = $.getJSON(file, function(json)
{
for (key in json)
{
var k = key;
var r = json[k];
$.extend(errs, check_item("#"+k,r));
}
});
return errs;
}
And... as you can probably guess, I get an empty object returned. My original idea was to use some sort of onReadyStateChange idea that would return whenever the readyState had finally hit 4. This causes my application to hang indefinitely, though. I need these errors to decide whether or not the form is allowed to submit or not (as well as to tell the user where the errors are in the application. Any ideas?
Edit. It's not the prettiest solution, but I've managed to get it to work. Basically, check_form has the json passed to it from another function, instead of loading it. I was already loading it there, too, so it's probably best that I don't continue to load the same file over and over again anyways. I was just worried about overloading memory. These files aren't absolutely huge, though, so I guess it's probably okay.
The inline-function in your $.getJSON call will be run when the Ajax call have finished. Do your work inside that (callback) function.
Your check_form function should accept a callback to execute when the information becomes available later.
function check_form(table, callback)
{
var file = "/models/"+table+".json";
var xhr = $.getJSON(file, function(json)
{
var errs = {};
for (key in json)
{
var k = key;
var r = json[k];
$.extend(errs, check_item("#"+k,r));
}
callback(errs);
});
}
Then, have callers of check_form provide a callback:
var table = getSomeTable();
check_form(table, function(errs)
{
for (var key in errs)
{
var value = errs[k];
// do something with key/value pair
}
});