Reading to JSON URLs with jQuery - javascript

I need to read two JSON URLs with jQuery, mangle them together and then proceed updating my UI from the JSON data.
With the two URLs in URLA and URLB and a global variable globalDataA I tried:
function useBothData(dataB) {
// use dataB and globalDataA
};
function useDataA (data) {
globalDataA = data
$.getJSON (URLB, useBothData);
};
$.getJSON (URLA, useDataA);
The idea is that after loading the 1st URL I load the 2nd and then work with them. However this does never seem to return. (I get the Brwoser warning "Script takes too long".)
How can I arrange jQuery's getJSON calls for the two URLs (and their success functions), so that I can then use their data in finally one function?

You can use the callback function of getJSON
$.getJSON(URLA, useDataA, function(dataB) {
//useBothData = globalDataA + dataB
$.getJSON(URLB, useBothData, function(result) {
//do more stuff
})
});

Related

getJSON jQuery won't fill object

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
});
});

Fetch data from different urls using the same collection in backbone js

I have a collection which has to call 4 external apis Eg: http://www.abc.com, http://www.fgt.com, http://www.jkl.com and http://www.rty.com.
I have a Collection named Todos.js. Is there a way I can fetch the 4 apis together in a single collection since all the four apis would provide me the same model response
So the response I get from the 4 apis has the same data structure i.e. "name" and "link".
Is there a way I can append all the responses in the same collection? What is the best way to achieve this?
I think the way is to override fetch, where you make the Ajax call to each of the APIs. Store the returned partial sets in a temporary array, and when all 4 are complete, create the collection using this.reset. (You could use JQuery's Deferred I suppose, or just keep an internal count of how many calls have returned.)
Something like this:
var Collection = Backbone.Collection.extend({
fetch: function() {
this.completeCount = 0;
this.errorCount = 0;
this.temp = [];
this.urls = [ 'url1', 'url2', 'url3', 'url4' ];
var self = this;
// make a $.get call for each URL and add
_.each(this.urls, function(url) {
$.get(url, { success: function(data) {
console.log("Got partial collection from " + url);
self.addPartial(data);
// alternatively, just call "self.add(data);" here
}, error: function(response) {
console.log("Oops, the Ajax call failed for some reason... ignoring");
self.completeCount ++;
self.errorCount ++;
} });
});
},
// add a JSON array that contains a subset of the collection
addPartial: function(data) {
this.completeCount ++;
var self = this;
// add each item to temp
_.each(data, function(item) {
self.temp.push(item);
});
// if all have been received, then create the collection
if (this.completeCount == this.urls.length) {
this.reset(this.temp);
}
}
});
Here's a Fiddle where I replaced $.get with a method that just returns dummy data after a short delay.
Response to comment
Adding the responses to the collection as they come in is probably better (it's easier anyway). Here's an updated Fiddle.
I know it's an old question, but if someone reaches in here this information may help.
To preserve the data previosly fetched by a collection, you can change the url and call the method fetch() any times needed with this options:
reset: false,
remove: false,
Like this
yourCollection.fetch({reset: false, remove: false, [other]: [wathever]})
And that's all, no need for overriding the method. (Maybe in 2012 it was necesary, dunno. The fact is that those options work for Backbone 1.1.2 or later). Be aware that im not sure if this will merge or just add the new data even if it's reppeated.
The documentation (http://backbonejs.org/#Collection-fetch) is a little confusing about the 'reset' option, because it says is settled false by default, perhaps that may only apply when the url remains static and single.

load json from file into object

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.

getJSON to string then loop through string

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)
});

How to cache the result of $.post-request in jQuery?

I have a small jQuery script that gets information by looking at an ID.
What is the best way to prevent that the same data are requested more than once (e.g. what's the best practices for caching in jQuery)?
I have tried to use $.post and $.ajax with option "cache" set to true, but the request is being sent more than once.
Is it better to save collected data and use sets to see whether you'll have to request it or not?
Any ideas and suggestions are welcome!
If it matters, I use ASP.Net MVC on the server-side.
The cache option you saw on the documentation, refers to the browser's cache.
You can implement a pattern of self-memorizing functions in many ways, the goal is that the function result for determined argument (id in your case) is only computed once.
Since you are using an Ajax request, I would suggest you to use a callback argument also, e.g.:
var getInfo = (function () {
var cache = {}; // results will be cached in this object
return function (id, callback) {
if (cache[id] != null) { // if exist on cache
callback(cache[id]);
return;
}
// doesn't exists on cache, make Ajax request and cache it
$.post("info.url", { "id": id }, function (data) {
cache[id] = data; // store the returned data
callback(data);
});
};
})();
Example usage:
getInfo(5, function (data) {
alert(data);
});

Categories

Resources