performing two success handlers on Ajax requests - javascript

I'm building a web application which has a lot of ajax requests scattered around all templates
I'm using ajaxSetup on main template, from which all other templates will inherit. In this ajax setup I do some pre and post processing.
//on main.html
$.ajaxSetup({
beforeSend: function (xhr)
{
//stuff
},
success: function (data)
{
//other stuff
}
})
Each ajax request, has a success handler of it's own, which must also be performed.
The problem is, that the success handler of the ajax requests will overide the global one defined in ajaxSetup.
//on specific.html
$.ajax({
success: function (data){
//request specific request handler which overrides $.ajaxSetup.
}
})
My question is, is there anyway I can work around this replacement? I didn't want to have to write the same code, or function call on each of the individual ajax requests.
thanks in advance

You could use ajaxSuccess to accomplish this http://api.jquery.com/ajaxSuccess/:
$( document ).ready(function(){
$(this).ajaxSuccess(function( event, request, settings ) {
console.log("Global Success")
});
$.ajax({method: "GET", url: "/echo/json",success : function(e){
console.log("Success");
}});
});
http://jsfiddle.net/Jpv5P/1/

Related

POST request on Ajax Complete

I am trying to do a token exchange after every AJAX request performed on my site.
To do this, I am currently using the jQuery function .ajaxSuccess.
My problem is, whenever I try to perform an AJAX request within this function, it's obviously seeing it as a success and is this creating a recurring function.
How can I make a one-time AJAX request situated within this function which only runs once?
I.e. like so:-
$(document).ajaxSuccess(function() {
$.post("somewhere", {some: "data"}, function(data){
console.log(data);
});
});
You can check, if you actually need to make an AJAX request in your ajaxSuccess handler like so
$(document).ajaxSuccess(function(event, xhr, settings) {
if (settings.url != "somewhere") {
$.post("somewhere", {some: "data"}, function(data){
console.log(data);
});
}
});

How to call code-behind method from 'success' in ajax callback?

How to modify below code to use 'success' to call testMethod() in code-behind ?
I need to wait for return value from testMesthod() and process it.
$.ajax( {
url : 'myPage.aspx/testMethod',
type : "POST",
contentType : "application/json; charset=utf-8",
data : "{'name':'" + aNb + "'}",
dataType : "json"
}).done(function() {
alert("ok");
}).fail(function() {
alert("not ok");
});
Above code does not work because somehow latest JQuery version (1.10.1) gets overwritten by 1.3.2.
Thank you
You would need to pass the callback function to the function that wraps your $(ajax).
function getData(ajaxQuery, callBack){
var ajaxHREF = 'your url';
$.ajax({
url: ajaxHREF,
type: "post",
data: ajaxQuery,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json");
},
success: function(response, textStatus, jqXHR){
var jsonData = $.parseJSON(response);
callBack (jsonData);
},
However, a much better way of doing this is the global success event. It is better because you have all of the properties of the call available to you to enable dynamic processing of the results. Create the global success event inline = $(document).ajaxSuccess this gets called for all jquery ajax success events so you need to differentiate which calls apply to your specific handler (to each global handler).
$(document).ajaxSuccess(function(event, xhr, settings) {
var query = settings.data;
var mimeType = settings.mimeType;
if (query.match(/ameaningfulvalueforthishandler/)){
if(mimeType.match(/application\/json/)){
var jsonData = $.parseJSON(xhr.responseText);
}
}
}
Thank for replies, but I still do not see how callbacl can help me.
I need to call webmethod in code-behind: testMethod()
Ajax call does it, url = "myPage.aspx/testMethod" will 'call' webmethod testMethod(),
but it's asynchronous and returns quickly into 'success' section of ajax call.
But, I need to Wait for testMethod() to finish processing, retrieve result returned by testMethod() and process it.
Asynchronous ajax will return us into 'success' without waiting for testMethod() to finish,
and we will not get any data in response.
So, how callback helps me to achieve it?
function getData(ajaxQuery, callBack){
var ajaxHREF = "myPage.aspx/testMethod";
$.ajax({
url: ajaxHREF,
type: "post",
data: ajaxQuery,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json");
},
success: function(response, textStatus, jqXHR){
var jsonData = $.parseJSON(response);
callBack (jsonData);
});
Thank you
#Karen Slon - If I understand the question correctly, I think you need to conceptually separate the client side from the server side. The callback in .success/.done or global ajaxSuccess event enable your web page to initiate the request and keep on processing while the server side is processing your request 'myPage.aspx/testMethod'. When it completes successfully it returns to the success event. Now if testMethod does not return anything then you will find yourself in the success event event without a result. But you cannot get there unless web method testMethod has completed successfully and returned control. The .done event in your example only has alert("ok");. What makes you believe that the web method testMethod is not complete when the .done event occurs?
Look at these posts for better examples:
jQuery.ajax handling continue responses: "success:" vs ".done"?
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
http://api.jquery.com/category/deferred-object/

jQuery re-send ajax call after success

I want to be able to re-send an AJAX request (using jQuery) after is has been completed. This was my initial implementation
$.ajaxSetup({
complete: function(xhr, status) {
$.ajax(xhr)
}
});
But it seems as though I haven't understood the documentation as this doesn't fire off a request to the same URL.
Is there a way to complete this?
(p.s. I understand that if the above example was to work, that it would be an infinite loop of the same ajax request, this has been reduced for example purposes only :) )
Just do
$.ajax({
url: "foo.cfc",
success: function(){
$.ajax(this);
}
})
this is the settings passed in.
The same works for completed, but your question title asks for success.

How do I intercept data after ajax call, converse to jquery.ajaxPreFilter

I would like to intercept and modify data from the server before the ajax success callback is executed
I have this code:
jquery.ajaxPrefilter(function (options, originalOptions, jqXHR) {
// Modify options, control originalOptions, store jqXHR, etc
});
and would like the equivalent:
jquery.ajaxPostfilter(function (dataComingFromServer) {
dataComingFromServer.applyMyModifications();
});
ajaxPostfilter does not exist though - is there another way of intercepting the response from the server before it reaches event handler:
This question is related to this one - but it was not answered:
How can I intercept ajax responses in jQuery before the event handler?
If you want to use a standardised function to modify your data before the specific callback, you can use a pattern like this:
// Boilerplate to modify your data
function preprocess(data){
data.foo = "bar";
return data;
}
// Your specific handlers
function logdata(data){
console.log(data);
}
function writedata(data){
document.write(data);
}
// AJAX requests
$('#foo').load('url1', function(data) {
logdata(preprocess(data));
});
$('#bar').load('url2', function(data) {
writedata(preprocess(data));
});
Of course, this can be baked into a method that wraps the traditional .ajax, making it more convenient to use.
Note that the dataFilter option pointed out by KevinB serves a similar purpose, but it is limited to the .ajax method. If you wanted to set a global filter for AJAX requests, you would use:
$.ajaxSetup({
dataFilter: preprocess
});
If you want to handle the data coming back from the server before the event handler, use datafilter:
jquery.ajaxSetup({
dataFilter: function (data, type) {
//modify the data
return data;
}
});

ajax calls to controllers. How to indicate success, complete, and error

If I make an ajax call to a controller.... what needs to happen in the controller so that the ajax call then calls
1) complete:
2) success:
3) error:
4) any other callbacks that exist.
For ex. I have this ajax call.
$.ajax({
url: "/ContactPartial/ContactUs",
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
complete: function () { },
success: function () { },
error: function () { }
});
In other words, what can I do inside /ContactPartial/ContactUs to control which of the 3 (complete,success,error) gets called after the controller code executes.
Also, how is this related to related to return Json(new {some: data});
These three callbacks are related to the status of the Ajax call. These are called depending on success of the call. For complete details refer to the documentation
So, if the server responds with a success (200), then both the Success and the Complete handlers would be called. In the complete handler, you might put some code to dismiss a modal window (regardless of success or error), and in the success function, you might put code to let the user know the call was successful, reload a grid view, etc. Also, keep in mind that the callback functions don't have to be anonymous functions, they can be defined functions that are shared among several Ajax calls.
EDIT:
If you are wanting to force the server to generate an error, take a look at:
The HttpResponse class, specifically the StatusCode property
This SO post explains more too (generating a 401 error)

Categories

Resources