Is there any way to "cancel" the promise.done() from being called? - javascript

The idea is, whenever a certain scenario happens in server, I want the HTTP call to be recognised as success by the browser, but still not call the done() function of the deferred object returned by $.ajax call.
To handle this I was thinking of returning a custom HTTP code (2XX, ensuring not any of the standard HTTP success codes) from my server.
This code will be generic, and will be returned by all the server side calls that encounters this scenario
Now, in my javascript code, I want to make sure that if the return code is my custom 2XX, the promise.done method should not be called.
I was guessing something like this should work.
$.ajax({
/* url parameters here */
success: function (data, textStatus, jqXHR) {
/*This code is to handle custom return code 289
* This code ensures that if there is an issue in getting data from api side
* the actual promise.done() method is not called. because that would cause Javascript error*/
if(jqXHR.status === 289){
// Stop promise.done from being executed
// or override the promise.done function to something harmless
};
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (options, status) {
},
timeout: 60000
});
Is there any way to "cancel" the promise.done method being called, in a standard way?

Related

How to identiy caller mathod from ajaxSuccess in Jquery?

Let me say, I have a document and it have 10 Ajax function calls to the web method. So, I have update in common for all ajax success so, i used
$(document)ajaxSuccess()
It done the job well.
But, in among the 10 ajax function, I need to ignore only one function's success call to the method or need to handle it different way.
So is there a way to find the caller method details in the ajaxSuccess function and handle.
Thanks in advance.
Happy Coding.
You can use beforeSend option of $.ajax() settings object to set a Boolean flag at jqXHR object and if condition at success callback to check for flag.
setTimeout(function() {
jQuery.ajax({
url: "/path/to/server",
beforeSend: function(jqxhr, settings) {
jqxhr.not = true;
}
})
}, duration);
function commonForAllAjaxSuccess(data, textStatus, jqxhr) {
if (!jqxhr.not) { // do common stuff }
else { // do not do stuff }
}
jQuery(document).ajaxSuccess(commonForAllAjaxSuccess);

Invoke jQuery ajaxSuccess (or any global AJAX event) even if the local success (or any local AJAX event) throws an error

It is not mentioned in the docs, but apparently if the local AJAX success handler throws an error, even the global ajaxSuccess handler is not invoked. Is there a way around this mechanism cause if you want to distribute a JS library or util function that does something on ajaxSuccess, you can't necessarily have control over the success handler and make sure it does not raise an exception.
$(document).ajaxSuccess(function(ev, jqXHR, settings) {
console.log('ajaxSuccess called!'); // does not get called
});
$.ajax({
'url': '/',
'type': 'GET',
'success': function (response) {
console.log('success called!');
throw new Error();
}
});
CodePen: http://codepen.io/anon/pen/Ldybr
Here is the documentation that partially explains the issue you're facing:
Events
...
success (Local Event)
This event is only called if the request was successful (no errors from the server, no errors with the data).
ajaxSuccess (Global Event)
This event is also only called if the request was successful.
error (Local Event)
This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
ajaxError (Global Event)
This global event behaves the same as the local error event.
This is the normal flow of events, i.e. any global event is called after local. But in case any callback throws exception, no other callback is called, because jQuery internally doesn't wrap the callback in try-catch (you may do this locally in your callback though).
Another solution, as I've mentioned in comments, is dataFilter property of ajax options, which allows you to perform needed actions before any local callback (success or error) is called. Here is demo from my comments to the question, just in case:
$.ajaxSetup({
dataFilter: function(data, type) {
console.log('dataFilter called!');
return data;
}
});

Equivalent of onLoad in jQuery?

I have this function when I am doing a request for an image in javascript
xhr.onload = function(e) {
console.log(e);
};
this works as intended, but when I try and do something like this in jQuery
success: function (data) {
console.log("hi");
}
nothing gets printed. I inspect the request using the developer chrome window and the request works fine but for some reason is not calling the function within the success clause. Is there any way that I can make that function be called regardless of how the request executes? Like onLoad.
Thanks!
You want complete, as it executes regardless of the response status:
complete: function (data) {
console.log("hi");
}
complete
[...]
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
Another alternative -
$(document).ready(function(){
//Write code here
});

Call a function everytime and AJAX request is processed and returned from the server

I have a application where there are numerous number of ajax calls to the server.
Now I want to audit the response that comes from the server (This requirement poped up after the ajax code was laid).
So I have a function that would audit the response data, only problem is how can I get the data to be sent to the function which now sits separately.
I don't want to do the laborious work of adding the line of code for calling the function in each ajax call.
Is there easier and general way out. Somehow I could detect when a response come back and then process the response.
Using both traditional javascript method as well as jquery ajax calls in the system. (The app has been getting changes from a long time and has changed hands a lot so the new things get added and the older ones never get removed)
Wrap your ajax calls with a helper function and use it throughout your code.
An (untested) example:
MyApp = MyApp || {
logRequest: function _logRequest(settings, response) {
// Log your response
},
ajax: function _ajax (settings) {
var that = this;
// Log attempt request here?
// Example of logging the success callback (do similar for error or complete)
if (settings.success) {
// A success handler is already specified
settings.success = function (data) {
that.logRequest(settings, data); // Log the response
settings.success(data); // Call the original complete handler
};
} else {
// No success handler is specified
settings.success = function (data) {
that.logRequest(settings, data);
};
}
return jQuery.ajax(settings);
}
};
I favour this mechanism for lots situations where I want to reduce boilerplate. I only have to modify the state of the MyApp object which is my own (named appropriately for the application), so it is sort of an interface that allows you to intercept function calls without modifying other global objects. You can also swap this functionality out with something else very easily without having to update your references everywhere, which could be useful in a lot of other situations as well.
Using .ajaxComplete() should be enough to catch the onComplete event for all AJAX requests made through jQuery. Isn´t that what you´re asking for?
$('.ajaxRequest').click(function(event) {
event.preventDefault();
$.getJSON(
'/echo/json/',
this.id,
function(data, textStatus, jqXHR) {
console.log(data, textStatus, jqXHR);
}
);
});
// Listen to all ajax requests
$("#log").ajaxComplete(function(event, request, settings) {
console.log(event, request, settings);
});​
View demo.

Override Ajax Success event

I am trying to override the jQuery ajax function to handle a default action on a success event but also executing the callback function that i am using in the options parameter.
What the purpose is there is tags returning in the response that I always want to strip out of the response for use elsewhere.
The scenario is:
Ajax submit
Ajax Success
--DEFAULT SUCCESS ACTION
--Call Ajax Success Callback
Can anyone help?
I have tried extending
jQuery.ajax
jQuery.ajaxSuccess
jQuery.ajax.done
The code I have is:
var _ajaxSuccess = jQuery.fn.ajaxSuccess;
$.fn.extend({
ajaxSuccess: function (a)
{
_ajaxSuccess.apply(this, a);
}
});
There is the global ajaxSuccess callback:
Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.
That will let you call your own function on every successful AJAX call without interfering with the usual success callbacks.
There are various other global AJAX event handlers that you might want to look at too.
If those callbacks don't have the right timing or capabilities for you, then you could write your own wrapper for $.ajax and use that:
function wrapped_ajax(options) {
var success = options.success;
options.success = function(data, textStatus, jqXHR) {
// Do whatever needs to be done here.
if(success)
success(data, textStatus, jqXHR);
};
return $.ajax(options);
}
You can do whatever you need to the usual success callback parameters before calling the original success callback. You'd call wrapped_ajax in exactly the same way as $.ajax. You could use the same technique to hook into the other callbacks as well.
try jQuery.ajaxSetup it may help you ,read about it here
Do like this:
$.ajaxSuccess(function(){
//somethingtodo
});
Mentioned in http://tutorialzine.com/2011/06/15-powerful-jquery-tips-and-tricks-for-developers/ heading twelve.

Categories