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/
Related
I am working on below Ajax code in JavaScript, I am trying to pop up a dialog box when the URL could not load the JSON properly the reason may be either expired token or incorrect token, in any case, I am expecting the code to hit the error or fail but it's not happening. When the URL could load the JSON successfully, success and complete blocks are being hit as expected but nothing is being hit when URL fails. I have tried to use async: false and tried to check with a boolean variable weHaveSuccess but console.log(weHaveSuccess); which is in the last line of the code is getting executing even before success/error is being executed and it seems to me like its still loading asynchronously. I would like to know why error block is not being hit when the JSON load from URL is getting failed.
My code
function checkUser(myURL, newAccessToken, weHaveSuccess) {
$.ajax({
type: "GET",
dataType: "jsonp",
async: false,
url: myURL + newAccessToken,
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
},
success: function (data) {
console.log("Hello 2 " + JSON.stringify(data));
weHaveSuccess = true;
console.log('Message from Success ' + weHaveSuccess);
},
complete: function () {
console.log('Message from Complete ' + weHaveSuccess);
}
}).done(function (data) {
alert("Success");
console.log(data);
}).fail(function (data) {
console.log(data);
alert("Failed");
}).always(function () {
alert("In Always");
});
console.log(weHaveSuccess);
}
Thanks in advance!
AJAX requests are asynchronous. It takes time for a remote request to be made and responded to. You will have to write your post-response code within the success function or call another function from there, not within the same scope as where the call is initiated.
I am taking a bit of a guess here about what your server returns on failure. An AJAX request success means simply that a 200 OK response was received, without any consideration of the contents of the data. If an error is simply a change in the data you will need do one of the following to show an error:
Have the server set a status code header on failure, perhaps 400 Bad Request.
In the success function look within your data for whatever error response you are expecting and trigger the alert() there.
First of all the console.log(weHaveSuccess); fires first, because the $.ajax() is asynchronous while console.log is not so ajax will be triggered and return the promise when finishes, but the browser will continue with the script.
In the jQuery ajax docs says:
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation.
It's hard to debug without seeing the response, maybe you can add some info from the network or a URL?
How about if you try the following:
Add the jsonp setting to your $.ajax() function for the callback that will handle the response and console.log there:
function myCallback(data) {
console.log(data);
}
$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: myCallback,
...
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);
},
});
In a javascript function I make a call to the server and get batches of 10 records back. I need to do this untill I've had all records.
To start I made a while loop where in the error callback of the ajax call I would end the while loop.
Halfway through I started to realize that that would not work, as the ajax call is async and I would thus fire loads of requests in the loop. I'm sure there is a standard pattern to do this but I don't know how.
How can I do the ajax call in a loop and perform it as long as the call is not returning an error?
Pseudo code I was building:
var stillRecordsAvailable = true;
while (stillRecordsAvailable) {
// get the next batch of records
$.ajax({
url: '/getrecords.json',
data: {data_set_id: dataset.id},
type: 'GET',
success: function(data, textStatus, xhr) {
// do something
},
error: function(xhr, textStatus, errorThrown) {
// nothing left to do
stillRecordsAvailable = false;
}
});
Thanks for pointing me in the right direction
You'd probably want to just wrap the ajax call in a function that is called on the ajax success callback:
function getRecords(data, textStatus, xhr) {
if (data) {}; // do something...
$.ajax({
url: '/getrecords.json',
data: {data_set_id: dataset.id},
type: 'GET',
success: getRecords
});
}
This will only work if your server/API returns an error when no more records exist; however, this may not be the best pattern. A more elegant way of tracking asynchronous event state is through a deferred/promise pattern. jQuery has a great implementation: http://api.jquery.com/category/deferred-object/
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)
EDIT: The original problem was due a stupid syntax mistake somewhere else, whicj I fixed. I have a new problem though, as described below
I have the following jquery.ajax call:
$.ajax({
type: 'GET',
url: servicesUrl + "/" + ID + "/tasks",
dataType: "xml",
success : createTaskListTable
});
The createTaskListTable function is defined as
function createTaskListTable(taskListXml) {
$(taskListXml).find("Task").each(function(){
alert("Found task")
}); // each task
}
Problem is: this doesn't work, I get an error saying taskListXml is not defined. JQuery documentation states that the success functions gets passed three arguments, the first of which is the data.
How can I pass the data returned by .ajax() to my function with a variable name of my own choosing.
My problem now is that I'm getting the XML from a previous ajax call! How is this even possible? That previous function is defined as function convertServiceXmlDataToTable(xml), so they don't use the same variable name.
Utterly confused. Is this some caching issue? If so, how can I clear the browser cache to get rid of the earlier XML?
Thanks!
See my comment. If you're using IE, GET AJAX requests are cached. jQuery can solve this for you by adding a random querystring variable to the request. Simply change your AJAX call to this:
$.ajax({
type: 'GET',
url: servicesUrl + "/" + ID + "/tasks",
cache: false,
dataType: "xml",
success : createTaskListTable
});
That will add the random querystring automatically, thus preventing the browser from caching the request.
Try defining your callback inline like this:
success: function createTaskListTable(data, textStatus, xhr) {
console.dir(data, textStatus, xhr);
}
If data is indeed being returned as null, you might get some insight from the other fields, especially xhr.
Note that error callbacks get called with (xhr, textStatus, errorThrown).