Modifying JSONP results before success callback - javascript

I'd like to load some JSON data from an external service. However, it provides
{ foo: ..., bar: ..., useful: {...} }
and what I really care about is in the "useful" part. I need to pass just that part to the success callback.
I'm trying to use Deferred to load from multiple data sources at once -- something like this. I'd like to retrieve the data, "massage" the result, and have just the "useful" part in the example above actually passed to the then callback. My understanding is that when you pass a Deferred to when(), the data goes directly to the callback passed to then(), so I need to hook into the process before it gets there.
I tried dataFilter but for JSONP that's not possible. Is there any other way to intercept these results? I can add some checks to my then() callback to handle cached data differently from the "fresh" results, but that sort of loses the magic of Deferred in the first place.
To clarify, this doesn't work:
$.when($.ajax({
url: "host/service",
dataType: "jsonp",
dataFilter: function(data, type){
return data.useful; // throws, data === undefined
}
})).then(function(usefulStuff){ ... });

You can call .pipe() to process the data and create a new Deferred:
$.getJSON(...).pipe(function(results) {
return ...;
})

Related

jQuery Ajax with async: false and return data

Im building a browser based application.
On window.load, i call a jquery AJAX GET function which is supposed to get me some gamedata from the server.
Once the data is there, i parse this data into my javascript and build some stuff up.
For that reason, i set async to false.
Now looking at this function, i want to call another function on ajax.success, but i want to use the freshly returned data as well as the data that was sent to this very function as a parameter (from another async ajax call).
How can i do this ?
thanks
window.onload = function(){
ajax.getFleets();
ajax.getShips(fleets);
manager.draw() // can only draw if both ajax functions have received data !)
}
getShips: function(fleets){
$.ajax({
type: "GET",
url: "getGameData.php",
datatype: "json",
data: {
type: "ships"
},
error: ajax.error,
success: ajax.mergeData, //want to pass fleets and returnData to this function
async: false
});
},
Also, on a general note, using async: false is the correct approach for this, right ?
thanks,
$.ajax will pass your callback function the result of the AJAX request, so you can use a simple anonymous function to get both parts in. Let's say you have your callback function defined like this:
ajax = {};
ajax.mergeData = function(fleets, ajaxResult) {
console.log(fleets);
console.log(ajaxResult);
};
You can define your callback function as:
function(result) { ajax.mergeData(fleets, result); }
Putting that all together, your getShips function will look like this:
ajax.getShips = function(fleets) {
$.ajax({
type: "GET",
url: "getGameData.php",
datatype: "json",
data: {
type: "ships"
},
error: ajax.error,
success: function(result) { ajax.mergeData(fleets, result); }
});
};
To answer your second question: async: false is a deprecated option, so you can't rely on it to work. It will also lock up the browser until the server responds, which makes for a really bad user experience. It's far better to use callback functions or promises to carry out an action when your AJAX requests complete. Here's a short summary of the promises concept that might be useful.
Which leaves the last, big question: how do we chain these calls together so getShips() depends on the result of getFleets(), and manager.draw() depends on both? With just two calls, you could get away with just using callbacks; getShips' success callback invokes getFleets, and getFleets' callback invokes manager.draw. This is the easiest way to get an A → B → C dependency chain working – but we could also use jQuery's promises, which might make our code easier to follow.
First, let's change getFleets to return the result of calling $.ajax:
ajax = {};
ajax.getFleets = function() {
return $.ajax({ /* Details elided here */ });
}
Next, let's update getShips to make an AJAX request for that data, and return a promise that returns the combined data:
ajax.getShips = function(fleets) {
return $.ajax({ /* Details elided again */ })
.done(function(ajaxResult) { return mergeData(fleets, ajaxResult); });
};
This is a bit trickier; $.ajax returns a promise that will eventually resolve to our ship data. When it does, we'll call the function in .done that returns the merged data. And that .done also returns a promise – so getShips is now returning a promise that will eventually return the merged data.
So now we can write our window.onload function to chain all these together, and only call manager.draw when all the data's available:
window.onload = function() {
ajax.getFleets()
.done(ajax.getShips)
.done(manager.draw);
}

How to know which $.ajax promise has resolved?

I'm using jQuery ajax to request data which will then be made into different kinds of charts or tables.
I've put the queries I want to run into an object and send the requests. runQuery() returns a jQuery promise. The data returned when the promise is done is correct. [Edit]Since the ajax requests run asynchronously they may not come back in the order they were issued [/EDIT] and I have no way of know which query the returned data was for.
function refreshData(){
for(var key in baseQueries){
runQuery(baseQueries[key])
.done(function(data){
console.log("Query data for "+key);
// want to call different charting functions
// based upon which results are returned
});
}
};
runQuery(obj) { // "public" function
var params = $.extend({},defaults,obj);
return sendRequest(queryUrl,params)
}
sendRequest(url,data,method){ // "private" function
method = method || "GET";
return $.ajax({
type:method,
url:url,
dataType:"json",
data:data
})
.fail(function(error){
console.log(error);
});
}
In this case the console logs the value of key during the last iteration over the baseQueries object. For example if there are three items in my baseQueries object and the the last item in my baseQueries object is
"This-is-the-last-query":"queryparam1,queryparam2,etc"
Then when all three of the ajax calls resolve I get three logs of "This-is-the-last-query". Which is not helpful because it doesn't tell me which query the data belongs to.
This is similar to the idea of the infamous javascript loop issue but I really don't see how the answer of attaching the value to a DOM element could be used here.
How do I match up which query call goes with which promise? How to I pass the key through the ajax call and return it with the promise data.
Edit
Don't think this is a duplicate of the indicated thread. I see how they are related, but not how to use that to solve this. Suggested duplicate doesn't mention jquery, ajax, promises, or asynchronous issues. It is also marked as a duplicate for another thread that doesn't mention any of those things either.
The solution shown either involves using the dom element to hold the information (which doesn't apply here) needed for the onclick or by adding a closure, but I don't see how to do that when there is already data being returned.
If you pass jQuery ajax a parameter that it knows nothing about, it ignores it and you can access it later.
Here we set a parameter for your extra value (mykey) then we have access to it later for the instance we are using:
function refreshData() {
for (var key in baseQueries) {
runQuery(baseQueries[key], key)
.done(function(data) {
console.log("Query data for " + this.myKey);
// "this" here is the ajax for which the promise (ajax) gets resolved,
// and we return that promise so it works here.
// want to call different charting functions
// based upon which results are returned
});
}
};
runQuery(obj,key) { // "public" function
var params = $.extend({}, defaults, obj);
return sendRequest(queryUrl, params,,key)
}
sendRequest(url, data, method, key) { // "private" function
method = method || "GET";
return $.ajax({
type: method,
url: url,
dataType: "json",
data: data,
myKey:key
})
.fail(function(error) {
console.log(error);
});
}
if you want to check if jquery promise is resolved you can check with jqueryPromise.state() which returns either pending, resolved or rejected depending on state.
If you are sending multiple ajax requests and you want to know when they are completed you can put them into array ([$.ajax(...),$.ajax(...)]) and pass it to
$.when like
var requests = [$.ajax(...),$.ajax(...)];
$.when.apply($, requests).done(function() {
console.log('all requests completed');
});
if you want to build something complex with promises I would suggest using bluebird or less complex rsvp

Why does the jQuery success callback sometimes have 3 parameters and sometimes have only 1?

It appears there are two ways to construct a success callback for jQuery, one form having 3 parameters and the other having only 1. Which of these is correct, and why do both forms appear?
Look at the success function in the docs: http://api.jquery.com/jquery.ajax/
Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
So the success function can take 3 parameters: the data returned, the status of the response, and the XHR object. Most of the time, you only need the first parameter.
Maybe you are wondering why these two kind of ajax-using are both working?
$.post(url, callback-when-success);
$.post(url, data-to-be-posted, callback-when-success, server-return-datatype);
Let's have a look on the implementation(source code) of $.post()
jQuery.post = function( url, data, callback, type ) {
/** the trick is right here ! **/
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
In fact, the $.post() always expects four parameter, and if you omit the data-to-be-posted(should be in the 2nd-pos)parameter, and the success-callback is placed on the 2nd-position, then the data would be assigned as undefined and the success-callback would still be the success-callback.
The then and done methods don't care how many parameters your callback has. A jQuery Promise1 can resolve with multiple arguments, and all these arguments will be passed to your callback. Which and how many of them you actually want/need to use is your business.
Some examples:
the animation queue .promise resolves with a single argument, the elements collection.
the $.ready.promise resolves with the jQuery function
the internally used Animation promises resolve with two arguments
the $.ajax promise resolves with the success, statusText, jqXHR arguments
a $.when(promise1, promise2, promise3, …) promise resolves with arbitrarily many arguments
a promise.then(function() { return … }) promise resolves with the single … value
1: Notice that almost all other promise libraries put promises for single values only, see here for example.

Repeated Ajax calls resolving Deferred differently, how?

I am curious if I am using the deferred incorrectly and if not - is there a more eloquent way.
So, I am firing this ajax request multiple times during a persons page view. Now, I understand I can only resolve the deffered once, so I reset the "def" appropriately. But I am wondering if I can assign the ajax call to the variable, and pass in the unique identifier and resolve the deferred?
I need things to happen either on the success or error of the ajax request.
So, I have an ajax request.
// some code. I set some var.
var def = $.Deferred();
// more code
$.ajax({
dataType: "json",
url: url,
data: params,
success: function(d) {
// resolve my deferred and pass a unique identifier
def.resolved('onSucc');
},
error: function(d) {
def.resolved('onErr');
};
});
To something like?
var def = $.ajax({
dataType: "json",
url: url,
data: params,
success: function(d) {
// resolve my deferred and pass a unique identifier
return def.resolved('onSucc');
},
error: function(d) {
return def.resolved('onErr');
};
});
Also, is there a need to return a promise here? My code seems to work ok without it - but I am curious if I am missing out.
You are actually not using deferred correctly. Deferred objects are for creating promise chains from scratch when making a non-promisified API promisified. The way you're using it is called the deferred anti pattern.
Promises chain, so instead of reverting to callbacks and deferred objects, you can simply use the chaining function then that transforms a promise into a new promise:
return $.ajax({
dataType: "json",
url: url,
data: params,
}).then(function(result){
console.log("got result!", result);
return someTransformOn(result); // use return values, can also return promise
}); // error case gets handled for you
Which would let you do:
functionReturningAjax().then(function(transformedValue){
// access to transformed value here
},function(err){
// then accepts an optional second argument for errors, use it to handle errors.
});

Differences in jQuery's callback approaches [duplicate]

I have been working with jQuery and AJAX for a few weeks now and I saw two different ways to 'continue' the script once the call has been made: success: and .done.
From the synopsis from the jQuery documentation we get:
.done(): Description: Add handlers to be called when the Deferred object is resolved.
success: (.ajax() option): A function to be called if the request succeeds.
So, both do something after the AJAX call has been completed/resolved. Can I use one or the other randomly? What is the difference and when one is used instead of the other?
success has been the traditional name of the success callback in jQuery, defined as an option in the ajax call. However, since the implementation of $.Deferreds and more sophisticated callbacks, done is the preferred way to implement success callbacks, as it can be called on any deferred.
For example, success:
$.ajax({
url: '/',
success: function(data) {}
});
For example, done:
$.ajax({url: '/'}).done(function(data) {});
The nice thing about done is that the return value of $.ajax is now a deferred promise that can be bound to anywhere else in your application. So let's say you want to make this ajax call from a few different places. Rather than passing in your success function as an option to the function that makes this ajax call, you can just have the function return $.ajax itself and bind your callbacks with done, fail, then, or whatever. Note that always is a callback that will run whether the request succeeds or fails. done will only be triggered on success.
For example:
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'json',
beforeSend: showLoadingImgFn
})
.always(function() {
// remove loading image maybe
})
.fail(function() {
// handle request failures
});
}
xhr_get('/index').done(function(data) {
// do stuff with index data
});
xhr_get('/id').done(function(data) {
// do stuff with id data
});
An important benefit of this in terms of maintainability is that you've wrapped your ajax mechanism in an application-specific function. If you decide you need your $.ajax call to operate differently in the future, or you use a different ajax method, or you move away from jQuery, you only have to change the xhr_get definition (being sure to return a promise or at least a done method, in the case of the example above). All the other references throughout the app can remain the same.
There are many more (much cooler) things you can do with $.Deferred, one of which is to use pipe to trigger a failure on an error reported by the server, even when the $.ajax request itself succeeds. For example:
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'json'
})
.pipe(function(data) {
return data.responseCode != 200 ?
$.Deferred().reject( data ) :
data;
})
.fail(function(data) {
if ( data.responseCode )
console.log( data.responseCode );
});
}
xhr_get('/index').done(function(data) {
// will not run if json returned from ajax has responseCode other than 200
});
Read more about $.Deferred here: http://api.jquery.com/category/deferred-object/
NOTE: As of jQuery 1.8, pipe has been deprecated in favor of using then in exactly the same way.
If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done.
This is from jQuery official site:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
From JQuery Documentation
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to deferred.done() for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
(added in jQuery 1.6)
An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.
In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use
jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Categories