How to identiy caller mathod from ajaxSuccess in Jquery? - javascript

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

Related

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

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?

How to pass the scope to the callback?

I have the following code structure and I am trying to maintain the scope of "this" to the current object in the success and error callbacks.
I have tried using Apply function, but I am not sure how to use in my use-case and that's where I need some help.
Here is the code I have :
function navigateToDocumentList(record){
var self= this;
var handoutDocumentList=Ext.create('xxx.view.HandoutsDocumentListPanel');
var navigationView = self.getNavigationView();
navigationView.push(handoutDocumentList);
navigationView.getNavigationBar().show();
navigationView.getNavigationBar().setTitle(record.data.name);
var url = intermountain.constants.HANDOUTS_DOCUMENTS_OF_CATEGORY_SERVICE_URL+record.data.name;
self.makeAJAXCallWIthParams(url,
16000,
self.navigateToDocumentListSuccess,
self.navigateToDocumentListError,
self);
}
function makeAJAXCallWithParams(url, timeout, success, error, callbackObj) {
Ext.Viewport.setMasked({
xtype: 'loadmask',
message: 'Loading ...'
});
Ext.Ajax.request({
url: url,
timeout: 5000,
success: success.apply(callbackObj,[]),// I need to know how to pass the function arguments here as earlier I was just calling it by success and now I need to call it using apply function
failure: failure
});
}
Please let me know if I need to explain the problem better. Any input / hint would be appreciated.
Thanks for your time!
To answer your question about arguments, each function in Javasctript can access a list with all its arguments via the arguments pseudo-parameter:
success: function(){ return success.apply(callbackObj, arguments) }
However, its going to be simpler to use the bind method instead of apply or call.
success: success.bind(callbackObj),
failure: failure.bind(callbackObj)

How to extract ajax response data from the success callback

Sorry if this is a duplicate but I couldn't find any satisfying answers in the previous posts.
$(function() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
// Data received here
}
});
});
[or]
someFunction() {
return $.ajax({
// Call and receive data
});
}
var myVariable;
someFunction().done(function(data) {
myVariable = data;
// Do stuff with myVariable
});
The above code works just fine. However, this ajax request is made on page load and I want to process this data later on. I know I can include the processing logic inside the callback but I don't want to do that. Assigning the response to a global variable is not working either because of the asynchronous nature of the call.
In both the above ways, the 'data' is confined either to the success callback or the done callback and I want to access it outside of these if possible. This was previously possible with jQuery 'async:false' flag but this is deprecated in jQuery 1.8.
Any suggestions are appreciated. Thank you.
You can "outsource" the callback to a normal function, so you can put it somewhere, you like it:
$(function() {
$.ajax({
url: 'ajax/test.html',
success: yourOwnCallback
});
});
somehwere else you can define your callback
function yourOwnCallback(data) {
// Data received and processed here
}
this is even possible with object methods as well
This solution might not be idea but I hope it helps.
Set the variable upon callback.
Wherever you need to process the data, check if variable is set and if not wait somehow.
Try:
$(document).ready(function(){
var myVar = false;
$.ajax({
url: 'ajax/test.html',
success: function(data) {
myVar=data;
}
});
someFunction(){ //this is invoked when you need processing
while(myVar==false){}
... do some other stuff ..
}
});
Or
someFunction(){
if(myVar==false){
setTimeout(someFunction(),100); //try again in 100ms
return;
}
.. do some other stuff ..
}

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.

Callback in jQuery wrapper function

I have written a function that retrieves a html template, then binds data using jQuery.tmpl. I think it's fairly neat and tidy and encapsulates what I need and provides me a reusable function. My question however is can it be improved.
My main concern is what if the $.get method fails, and also how the callBack function is executed.
function Bind(templateURL, templateData, templateTarget, callBack){
var req = $.get(templateURL);
req.success(function(templateHtml) {
$(templateTarget).html(''); //clear
$(templateHtml).tmpl(templateData).appendTo(templateTarget); //add deal
callBack();
});
}
You can pass the result of tmpl() directly to html() to clear your target container and append the new content at the same time. You can also chain the result of $.get() into your success handler to avoid using a local variable:
function Bind(templateURL, templateData, templateTarget, callBack)
{
$.get(templateURL).success(function(templateHtml) {
$(templateTarget).html($(templateHtml).tmpl(templateData));
callBack();
});
}
If $.get() fails, nothing will happen since you do not register an error handler. What that handler would do is up to you, but you might want to display an appropriate message in an alert box or somewhere on the page.
Your second concern is less clear. As it stands, callBack will only be called on success, and without arguments.
You can use $.ajax to assign and error calback. ex:
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
Check the api http://api.jquery.com/jQuery.ajax/

Categories