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

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)

Related

imbricate two async calls

I am calling the twitch TV API to get users info from one endpoint and I want also to call another endpoint in the same API to check if those users are streaming live or not, but only if the first ajax call is successful. Can anyone give me a hint on how to do it?? My first call below:
var getUserInfo = $.ajax({
type: "GET",
url: "https://api.twitch.tv/helix/users/?login=ESL_SC2&login=freecodecamp&login=noobs2ninjas",
// contentType: ('application/x-www-form-urlencoded; charset=UTF-8'),
crossDomain: true,
headers: {
"Client-ID": "5k4g3q59o69v6p9tudn39v50ro1mux",
},
dataType: "json",
success: function (json) {
console.log(JSON.stringify(json, null, 2));
},
error: function () {
console.log("OOPS!!!");
},
})
The jQuery ajax function is built using the callback design to deal with its asynchronicity. You have two callbacks, success and error, one of which will fire when you receive a response from the Twitch API. If you want to make another ajax request depending on if your previous request was successful then you can simply write a very similar ajax request inside your success callback function pointing to the new location you are trying to acccess. I would recommend splitting that off into a separate function to maintain the readability of your code however.
The success function only runs if the call was successful.
Trigger the code for the second request from the success function.

which one should be used in case of jquery ajax call, success/ error callback or done()/fail() chain function

sometimes even if the ajax call has returned error, it calls done() chain function rather than fail().
so confused whether to use success/error callback or done()/fail() chain function.
for eg which one is advisable 1 or 2?
$.ajax({
url: someurl,
success: function(){
//some code if ajax request is successful
},
error: function(){
//some code if ajax request fails
}
})
$.ajax({
url: someurl
}).done(function(){
//some code changes
}).fail(function(){
//some code changes
});
These are interchangeable ways of doing an AJAX call in jQuery. The second method you describe uses promises, whereas the first method handles successes/errors as options on the AJAX call.

Jquery ajax response not calling Success method

I am pretty much new to ajax and working on jquery ajax request. Ajax callback is not calling success method. Interaction is between cross-site domains.
My AJAX request looks like
$.ajax({
timeout: 20000,
url: 'test.com',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
} });
There are no errors in this call.
This ajax request is not calling success function.Request is returning json data. it's just success method is not getting called.
This ajax request is not calling success function.
Get request is getting fired successfully. I can even trace the response in fiddler with 200 http response.For some reason success method is not getting called.
it's returning json object, which I've traced in fiddler
You're telling jQuery to expect a JSONP response, so it is trying to execute the JSON document as if it were a JavaScript script (because that is what JSONP is). This fails because it is not JSONP.
Either return JSONP instead of JSON or (assuming the server returns the correct Content-Type) remove dataType: 'jsonp',.
ok... I came here with the same problem... and when I read that specifying datatype:jsonp never calls success as a callback per #mondjunge from a comment above, it started me thinking about some behavior I saw earlier from my code and that maybe datatype:json might have the same behavior for what ever reason here too.
So after reading this page I took out my datatype declaration from my ajax request and my servlet returned the proper data payload, returned a 200, and jquery called the success function finally and modified my DOM.
All those steps happened except the last one until I removed my datatype from my ajax call. NOT what I was expecting!
Hopefully someone else can shed some light on why this happens... for now at least the few that don't lose their minds to this issue that find this post can do this in the mean time.
Check if your ajax is executed
Check it's status. If response code is != 200, than you should add error method also, for error handling.
Try this:
$.ajax({
timeout: 20000,
url: 'test.com',
method: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
},
error: function(xhr, error){
console.debug(xhr); console.debug(error);
},
});

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 JSONP randomly generated callback function

I'm using JQuery to make JSONP requests and the documentation is quite confusing.
I have several questions:
A JSONP call is always async, is that correct? So the async:false would be simply ignored?
If the jsonpCallback parameter is specified, this function will be executed when the data are retrieved. But right after, also the success callback will be executed. Jquery advices NOT to specify the jsonpCallback function(only for caching?). What is the role of this function in relation with the success function?
If the jsonpCallback is not specified a random callback function will be created and attached to the window object. Something like jQuery1360574548776335413_1776656584447, what is its role? How does it work? Does it have any relation with the success function?
Is the error callback never called?
Here's my code:
(function($) {
var url = "https://www.googleapis.com/books/v1/volumes/zyTCAlFPjgYC";
$.ajax({
type: 'GET',
url: url,
// JSONP always async?
async: false,
jsonp: "callback",
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
// Error never called?
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
function jsonCallback(json) {
$(".test").html(json.volumeInfo.title);
}
A JSONP call is always async, is that correct? So the async:false would be simply ignored?
That is correct
If the jsonpCallback parameter is specified, this function will be executed when the data are retrieved. But right after, also the success callback will be executed. Jquery advices NOT to specify the jsonpCallback function(only for caching?). What is the role of this function in relation with the success function?
The success function is your callback. Jquery generates a random function name usually. If, however, you're making several of the same requests and would instead like to allow the browser to cache calls, you can specify the function so that a randomly generated one is not created. Inspect the network requests and you'll see (as long as your server is set up to support it) that if you specify the name, you should get 304 - Not Modified (edit: on subsequent requests after the first), while other calls always return 200 OK
If the jsonpCallback is not specified a random callback function will be created and attached to the window object. Something like jQuery1360574548776335413_1776656584447, what is its role? How does it work? Does it have any relation with the success function?
Is the error callback never called?
That callback function should contain the code you put in success. The error event is fired if there is an error with the actual request, such as an invalid domain name, 401 server response, and etc.

Categories

Resources