Setting both $(document).ajaxSuccess and $.ajax().done() - ajax

I have several ajax calls and when they succeed I need, firstly, to do the same check for all of the responses and then, if the check does not fail, do different things with the responses.
At the moment I'm using success option in each of the calls and insert this check in each of the calls, like this:
$.ajax({
success: function (data){
if (response_has_errors(data))
{return}
// do stuff
}
});
So, I have this idea: use $(document).ajaxSucces() for doing the same checking and then use $.ajax().done() or success option with each of the calls.
But I need the handler in $(document).ajaxSucces() to always be executed first, and if it returns false, not to execute individual handlers.
How do I do that?

First you should make sure you server does not return a success status (200 OK) when the response is in fact an error. This saves you one step in your processing.
Then you could use jQuery's when() to process requests together.
$.when(
$.ajax(...), $.ajax(...), $.ajax(...), $.ajax(...)
)
.then(function () (result1, result2, result3, result4) {
// all requests have successfully returned
})
.fail(function () {
// handle error (inspect arguments)
})
.always(function () {
// stop throbbers or other clean up work if necessary
});
Be sure to thoroughly read the documentation on Deferreds if you've never used them before.
Note that you also can pass an array of jQuery XHRs using apply().
$.when.apply($, allReqests).then( /* ... */ );

I could suggest using "dataFilter" from $.ajax(): http://api.jquery.com/jQuery.ajax/
You can put some error handling in this dataFilter and if it fails - update some flag directly in the data, and have all "success" handlers check for that flag before executing.

Related

AJAX + jQuery Deferred: execution sequence

Task: get data from server with $.post, process them by method .success(), after that call some function.
var t;
$.when($.post("get_json.php", function(res) {
t = res;
}, 'json')).done(function() {
console.log(t);
});
Do I understand correctly that the Deferred method .done() is executed after .success is done (ie t = res)?
But why "console.log(t)" shows "undefined"?
Is .done() fires after request, but before .success()?
Passing a "success" callback to $.post() is an alternative to the (preferred) chaining of .done(...). Do one or the other, not both, then you don't need to worry about the execution order.
Also, unless you have a decent caching strategy for async data, you shouldn't be setting t as an outer var.
$.post("get_json.php", ...).done(function(t) {
console.log(t);
//do awesome things with t here
});
Caching would be something like this :
var asyncCache = {};
...
function get_t() {
return (asyncCache.t) ? $.when(asyncCache.t) : $.post("get_json.php", ...).done(function(t) {
asyncCache.t = t;
});
}
...
get_t().done(function(t) {
console.log(t);
//do awesome things with t here
}
$.when() is ONLY needed when you have multiple promises and you want to wait for all of them to complete. You simply don't need it at all for your single ajax call. You can just do it like this:
$.post("get_json.php").done(function(t) {
// use the results of the ajax call here
console.log(t);
});
In addition, your code example was using BOTH a success callback function AND a .done() handler. Pick one of the other, not both as they are different ways of getting a callback when the ajax call is done. I'd suggest the promise implementation above because it's more flexible. But, you could also use just the success handler:
$.post("get_json.php", function(t) {
// use the results of the ajax call here
console.log(t);
}, 'json');
Note, when you have an asynchronous operation like this, you need to consume the results of the ajax call in the success callback (or the promise callback) or call some function from there and pass it the data. You do not want to put the data into a global variable or a variable in a higher scope because other code will simply have no way of knowing when the data is ready and when it is not. Put your action in the callback.
If you have more than one ajax call that you want to wait for, then you can do it like this:
$.when($.post("get_json.php"), $.post("get_json2.php")).done(function(r1, r2) {
// use the results of the ajax call here
console.log(r1[0]); // results from first ajax call
console.log(r2[0]); // results from second ajax call
});

Extjs store load success handler not getting fired

I have a store load method which returns data via an ajax request. I can see that the data is being returned using Firebug, but my success handler is not getting called:
this.getCategoriesStore().load({params:{'id':d.data.category_id}}, {
success: function(category) {
console.log("Category: " + category.get('name'));
},
error: function(e) {
console.log(e);
}
});
I am returning a success parameter, along with the data:
{"success":true,"categories":{"id":5,"name":"Frying","section_id":2}}
Is there something missing or am I doing anything wrong?
Well I suppose you are looking for this:
store.load({
params:{'id':d.data.category_id},
scope: this,
callback: function(records, operation, success) {
if (success) {
console.log("Category: " + category.get('name'));
} else {
console.log('error');
}
}
});
It is not that obvious in the API that your additional params can be placed there too. But ExtJS often uses the config objects to wrap things up.
Edit to answer comment:
The short answer is: Yes
Now the longer version:
In case of the store it is up to you to directly provide anonymous (or concrete) callbacks or register events. Both will work the same in your situation here.
But you can only have one callback while you can have many events. In further scenarios you will find situations where events fits much better or where events are the only way at all. That will always be the case when you are listening. Here are some notes on that:
make use of the { single: true } property when you just need a callback once. Example: store.on('load', function(s) { /* do something*/ }, scope, { single: true }) The listener will be removed after it was called. This is needed cause of the use of a anonymous function, that cannot be removed.
make use of mon() in most cases where you bind listeners directly in class-definitions to ensure the listeners get destroyed along with the instance of the class.
Both will save you browser memory.
Try this:
store.load({
scope: this,
callback: function(records, operation, success) {
// the operation object
// contains all of the details of the load operation
console.log(records);
}
});
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Store-method-load according to the docs there is no success and error callback.
Another alternative to providing callback you can also add a "load" event listener on the store for the same effect.

How can I handle async calls when validating with Backbone.js (uniqueness specifically)

This is relevant for either client or server side apps using backbone. I am attempting to create a validation function with uniqueness checks to MongoDB or some REST call (depending on environment). Both of these calls are async by nature; however, I think I actually need to make it block here for validation purposes. If I don't return anything the validate function will assume validation passed.
My code currently looks like this on the server side:
isUnique: function (key) {
var dfdFindOne = this.findOne({key: this.get(key)}),
dfd = new Deferred();
dfdFindOne.done(function (err, result) {
console.log(result);
dfd.resolve(true);
});
return dfd;
};
... some stuff here....
I feel like I can do some sort of wait till done functionality here before I return... perhaps not though. I wish backbone provided a callback function or something or accepted some sort of deferred type thing.
validate: function() {
var result = undefined;
if(!this.isUnique(key).done(function(){
result = "AHHH not unique!";
});
return result;
}
A possible solution might be to force mongodb's native node client to call things synchronously. I think I can do the same with rest calls... This is probably a bad solution though.
You could call the ajax request and set async:false in this way the return will have value. However to use async:false is evil because could appear as the browser is locked. For server side maybe there are not always workarounds for set async: false
My recommendation is to use your own validation flow instead of Backbone.validate flow, because the validation flow of Backbone was made thinking for synchronous validations only. You could try something like this:
//Code in your Model
isUnique: function (callback) {
var dfdFindOne = this.findOne({key: this.get(key)});
dfdFindOne.done(function (err, result) {
console.log(result);
callback(result);
});
};
validate: function(callback) {
this.isUnique(callback);
}
//trying to validate before save
model.validate(function(result){
if( result == 'whatexpected'){
model.save();
}
});

Make jQuery ajax calls in order

I want to make a stack of Ajax calls in this way: call(n) starts after call(n-1) finished...
I cannot use async:false for many reasons:
some requests maybe jsonp (the most relevant)
I have other ajax requests that may work meanwhile..
The browser got blocked
I cannot chain my requests this way:
$.post('server.php', {param:'param1'}, function(data){
//process data
$.post('server.php', {param:'param2'}, function(data){
//process data
});
});
Because the number and params of the requests are dynamically created from user input.
A small example that illustrates my problem.
You will see that the server response order is random, what I want to achieve is to have it in order
Response to arg1
Response to arg2
Response to arg3
Response to arg4
Response to arg5
Response to arg6
Any help would be very appreciated, thanks.
Ok, jQuery Ajax returns a Deferred Object, this can help you achieve this.
Here is how to do it:
var args = ['arg1','arg2','arg3','arg4','arg5','arg6'];
deferredPost(0, 5);
function deferredPost(index, max){
var delay = Math.random()*3;
if (index<max){
return $.post('/echo/html/', {html:('Response to '+args[index]), delay:delay},
function(data){
$('#response').append(data+'<br>');
}).then(function(){
deferredPost(index+1, max);
});
} else {
return $.post('/echo/html/', {html:('Response to '+args[index]), delay:delay},
function(data){
$('#response').append(data+'<br>');
});
}
}
DEMO
Here I used then function.
I also recommend to read a little bit more about deferred objects, they can solve a couple of common problems.
This is a job for a queue.
var queue = ['arg1','arg2','arg3','arg4','arg5','arg6'];
function runQueueInOrder() {
if (queue.length === 0) { return; }
var arg = queue.pop();
var delay = Math.random()*3;
$.post('/echo/html/', {html:('Response to '+ arg), delay:delay},
function(data){
$('#response').append(data+'<br>');
}).then(function() {
runQueueInOrder();
});
}
runQueueInOrder();
You don't need to use jQuery's then for this to work if you've encapsulated the processing of the queue in a function. It's handy though. The code is destructive as it removes elements from the original array (but as they are processed, it's usually OK).
The method runQueueInOrder is called to initiate processing.
When there is no more work to be done, the function simply exits. (I've written a version that polls on a timer before, but that's not needed here).
The function grabs the next work arg, calls your post call syntax, and when done uses jQuery's deferred then callback to call the function again (to process the queue further if needed).
(I looked at the other answer and found it confusing to follow, so I took a simpler approach. Using my simple version, you can add new items as new work is discovered--or remove them.).

Significance of Reflection in AJAX-Based Applications

Ajax and Reflection
I am developing an ajax-based application and wondering, what role reflection plays or might play here?
Probably most importantly I am asking myself, if it would be a good approach to
handle all ajax responses through a single handler,
reflect or interpret the data or error
delegate further processing (e.g. where to inject the html) based upon the analysis.
Is this a budding procedure? What pros and cons come to mind?
Additional clearification
My current implementation, which I am not happy with, looks like this.
Register eventhandlers for user action, which lead to ajax requests.
For each request:
Determine which container is the target for the new content
Validate the ajax response
Pass the result to the appropiate rendering function if everything is as expected
Here is an example
function setGamedayScoringChangeHandlers() {
$("#community").delegate("div.community div.nav", "click", function() {
var orderId = $(this).html();
var communityId = $(this).closest('.communityView ').dashId();
requestGamedayScoringByOrderId(communityId, orderId);
});
}
function requestGamedayScoringByOrderId(communityId, orderId) {
var $targetContainer = $('#community-' + communityId + '-gameday');
$.ajax({
url: '?api=league&func=getGamedayScoringByCommunityIdAndOrderId',
data: {
communityId : communityId,
orderId : orderId
},
success: function(result) {
// custom indicator, that sth. didn't work as supposed
if (result.success === false) {
// a php error couldn't be handled as expected
if (result.error === 'phpRuntimeError') {
// ..
}
// ..
}
else {
renderGamedayScoring(result, $targetContainer);
}
}
});
}
Question
How can this and especially the redundant error checking be simplified? Could Reflection, in a sense of: "Is the response valid? And what does the error message say or data look like?" be a reasonable structure do deal with this? Additionally: Is the "coupling" of the actual ajax request and determing the $targetContainer a "normal" procedure?
Many thanks,
Robson
Yes I think register ajax handler trought one pipe is a good way, because it is more easy to control, you will have less redundant code and less boarding effects. If I look at your code comments it seems the response is not as you expect. I use to do like this for controling a group of ajax request talking with server script. I build one request object like :
// myscript.js
var rqPHP = {
url:'php/dispatcher.php', type:'POST', dataType:'json',
success:function(json, status, jXHR){
//console.log('rqPHP.succes : ', json);
if(!json) return console.warn('[rqPHP.success] json is null');
if(!json.cmd) return console.warn('[rqPHP.success] json.cmd is null');
if(!json.res) return console.warn('[rqPHP.success] json.res is null');
if(json.err && json.err.length){ console.warn('[rqPHP.success errors cmd:'+json.cmd+'] '+json.err);}
// so if no errors, dispatch actions based on original command asked
switch(json.cmd){
case 'loadfile' :
// do whatever with response
break;
case 'savefile' :
// do whatever with response
break;
}
},
error:function(jXHR, status, err){
console.warn('[rqPHP.error] ', status,',',err,',',jXHR.responseText);
}
};
then when use this object trought all my group of different actions and I precise wich action and arguments I pass. I use to ask for a json data so I am able to receive an easy parsing response, so I am able to return the original command asked, and some details on errors that may occured for example, and when I need to fire the request :
// myscript.js
rqPHP.data = {'cmd':'loadfile', 'filename':'file.dat', 'arg2':'other argument'};
$.ajax(rqPHP);
Then an example of one server script that will respond :
// dispatcher.php
$pv = $_POST;
$res = '';
$err = array();
// you check the command asked for :
switch(strtolower($pv['cmd'])){
case 'savefile' :
// do whatever
break;
case 'loadfile' :
// do whatever
if(any error){
$err[] = $loadError;// push error with whatever details you'll retrieve in javascript
}else{
$res = ',"res":"'.$dataLoaded.'"';// format json response so you'll check the var exist
}
break;
}
$jsonRes = '{"cmd":"'.$pv['cmd'].'"'.$res.',"err":"'.implode('|', $err).'"}';// json result
print $jsonRes;
They may be some errors, it is just for the principe, I hope that will help, just some last advices :
you should better use the requestObject.data to pass any arguments instead of setting the url like you did, this is much more easy because jQuery does the properly encoding work
you may use POST so the url stay clean, post vars are 'hidden'
in your case, because you may want to centralize server actions with ONE server script, you should use 'json' as dataType because it is much easier to retrieve details from the response, such errors. You have to distinct the ajax error that is trigger when the url doesn't exist, or access denied, well when the server replies it just can't respond to this request, and distinct the properly response of your server script, I mean the script responds well but it may occur an command error, for example for a 'loadfile' command, the argument fileUrl may be wrong or unreadable, so the action is done but the response will be not valid for you...
If you plan to fire many loads for differents parts (I mean you may don't wait response for an ajax before loading a new one), it should be better to set main success and errors functions for keeping centralization and then build one new request object each time you make a load
function rqSuccess(json, status, jXHR){
// put same checking code as before, then you can also retrieve some particular variables
// here, 'this' should correspond to the request object used for the $.ajax so :
console.log('myTarget is : ', this.myTarget, ' , myVariable is : ', this.myVariable);
}
function rqError(jXHR, status, err){
// put same checking code
}
// then each time you want make one or many independant calls, build a new request object
var myRq = {url:'dispatcher.php',type:'POST',dataType:'json',
success:rqSuccess,
error:rqError,
myTarget:$('#myblock'),// any variable you want to retrieve in response functions
myVariable:'Hello !',// after all it is an object, you can store anything you may need, just be carefull of reserved variables of the ajax object (see jQuery $.ajax doc)
// the data object is sanitized and sended to your server script, so put only variables it will need
data : {'cmd':'loadfile',...}
}
$.ajax(myRq);
// you may load an other independant one without waiting for the response of the first
var myRq2 = {...myTarget:$('#anotherblock'), data:{'cmd':'anotheraction'}...}
$.ajax(myRq2);
As a first step, you should change the error handling on the serverside to produce a non-OK/200 response for error cases, e.g. throw a 500. Then have that handled as an actual error on the clientside, along with other errors, instead of putting it through the success-callback.
That way you can use jQuery's abstractions for global error handling: http://api.jquery.com/ajaxError

Resources