I'm making an ajax post request with success, failure and status code handlers. However, when the request fails with a 400 error, part of the success function is still called. Could someone please tell me why?
$.ajax({
type: "POST",
url: saveToGetTalentUrl.url,
data: JSON.stringify(candidateList),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#save_to_getTalent").replaceWith("Saved to getTalent");
alert("New User " + response.candidate.full_name + " created successfully");
console.log(msg);
//normalExec(response, msg);
},
error: function (errormessage) {
console.log(errormessage);
},
statusCode: {
400:function(){
alert(errors.err400);
},
401:function(){
alert(errors.err401);
},
403:function(){
alert(errors.err403);
},
500:function(){
alert(errors.err500);
}
}
});
}
When the call fails with a 400 error, the error from statusCode is displayed and the error is logged from the error function, but at the same time, the line $("#save_to_getTalent").replaceWith("Saved to getTalent"); is also called. I dont understand why
Try set async: true to see what happens.
See this part in the jQuery documentation for ajax:
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
So, the request by default (async: true) are sent one by one, not all together. If the POST takes a while, you may see the callback function executed before the POST request returned completely. When the first line of success is executed, it is blocked because you have a dialog popped up; meanwhile, the statusCode part is also executed; it continues to the end because nothing is blocking there.
Debug with a dialog is not the best solution because it always blocks; you can try to change some element's value to see the execute order, like changing an <input>'s value, append a number to see if the whole number string changes or not, to see if there is a race condition of success and statusCode.
Something like:
$.ajax({
data:
url:
success: function(returned, status, xhr) {
$('#testInput').val($('#testInput').val() + "1");
},
error: function (errormessage) {
$('#testInput').val($('#testInput').val() + "2");
},
statusCode: {
400:function(){
$('#testInput').val($('#testInput').val() + "3");
},
401:function(){
$('#testInput').val($('#testInput').val() + "4");
},
403:function(){
$('#testInput').val($('#testInput').val() + "5");
},
500:function(){
$('#testInput').val($('#testInput').val() + "6");
}
}
});
Related
I'm making multiple REST calls via Javascript to determine if a user is in several Sharepoint groups.
If the user is not in the group, the REST request returns a status of 500, along with a message saying "user cannot be found".
When an error is returned, I resolve my promise with "false", so my function works ok.
But - every REST response of 500 puts an error entry in the Javascript console - is it possible to suppress those entries?
I know they don't impact the function, but it clutters up the console.
function IsUserInGroupNumber(permissionRequested,userEmail,groupNumber){
var deferred=$.Deferred();
var url=L_Menu_BaseUrl+"/_api/web/sitegroups("+groupNumber+")/Users/getByEmail('"+userEmail+"')/Email";
$.ajax({
type: 'GET',
url: url,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json; odata=verbose");
},
processData: false,
success: function (data)
{
deferred.resolve({requestedPermission:permissionRequested,groupNumber:groupNumber,hasPermission:true});
},
error: function(data){
//user not found in the group returns a 500 error - but return value of 'false'
deferred.resolve({requestedPermission:permissionRequested,groupNumber:groupNumber,hasPermission:false});
}
});
return deferred.promise();
}
The service shouldn't respond with a 500 status code. That means something on the server is failing. You can't control how the JavaScript console / browser interprets and resolves an error or status.
Also, as of jQuery 1.5, $.ajax already returns a promise: http://api.jquery.com/jquery.ajax/
You could simplify your code a great deal with something like:
function IsUserInGroupNumber(permissionRequested, userEmail, groupNumber){
return new Promise(resolve, reject) {
$.ajax({
type: 'GET',
url: L_Menu_BaseUrl + "/_api/web/sitegroups(" + groupNumber + ")/Users/getByEmail('" + email + "')/Email",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
},
processData: false,
})
.done(function() {
resolve(true)
})
.fail(function() {
resolve(false)
})
}
I have an Ajax request which changes the content of an input field on success. That input field triggers another series of Ajax requests on change. The code works, but according to the console in Chrome, it is reported that "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience". It appears this error message indicates that synchronous requests are being made.
Here is the code:
$.ajax({
type: 'GET',
url: '/widgets/test',
async: true,
success: function (response) {
$("#widgetData").val(JSON.stringify(response));
$("#widgetData").trigger("change");
},
error: function (xhr, textStatus, errorThrown) {
console.log("There was a problem requesting the widget endpoint!");
}
});
$("#widgetData").change(function () {
var obj = jQuery.parseJSON($("#widgetData").val());
$.each(obj, function (id, url) {
$("#mainContent").append("<div class='widget' id='widget" + id + "'></div>");
$("#widget" + id).load(url);
});
});
I intend all of the requests to be asynchronous and believe that what I have written should accomplish that task. Please help me determine what is wrong, and why I am getting the aforementioned error!
It appears that your first ajax request is setting async flag to false. You can change that call to following
$.ajax({
type: 'GET',
async: true,
url: '/widgets/test',
success: function (response) {
$("#widgetData").val(JSON.stringify(response));
$("#widgetData").trigger("change");
},
error: function (xhr, textStatus, errorThrown) {
console.log("There was a problem requesting the widget endpoint!");
}
});
This should fix your warning message
When I execute the following code from localhost, for some reason jQuery enters the success function call, when really, I am getting a cross-domain issue (CORS isn't enabled on thirdpartydomain.com and I can't change it). The value of result is undefined.
var statusCheckUrl = "https://www.thirdpartydomain.com/webchat/live?action=avail";
$.ajax({
crossDomain: true,
dataType: "script",
url: statusCheckUrl,
success: function(result) {
console.log("result is: "+result);
eval(result);
},
error: function (jqXHR, textStatus, msg) {
unavailable();
},
timeout: 2000,
cache: false
});
I would have thought that the error function would be executed in this instance. Can you tell me why it's entering the success function call?
I am using jQuery 1.10.2.
I am beginner to jquery ajax. My below ajax code was working fine when I was using async: false, but due to problems in firefox I removed it after referring this link(I was facing the same issue). Now it is not working. not even showing any errors.
Here is my code:
try {
_ajaxCall = $.ajax({
url: URL,
type: "POST",
data: "drqlFragment=" + text,
//async : false,
cache: false,
headers: {
accept: "application/json",
contentType: "application/x-www-form-urlencoded"
},
contentType: "application/x-www-form-urlencoded",
//processData : true,
success: function (data, textStatus, jqXHR) {
var resData = data.suggestions;
for (var i = 0; i < resData.length; i++) {
sugData.push(resData[i].keyword);
}
},
error: function (response) {
//Error here
alert('hello');
}
});
} catch (e) {
alert(e);
}
The above code is neither executing success nor error. I even tried to catch the error by keeping try catch block but no use.
The problem was that I was doing manipulations outside the success callback function. It was working fine when I used async: false. that means the ajax call will be synchronous. When I removed async: false, the manipulations which I was doing outside the success callback function were not working. The problem was because of asynchronous behaviour of the ajax call. When calling a ajax call asynchronously, it will not flow as the code priciple i.e step by step and top to bottom but it can happen anytime. So, I was not able to get the desired output.
When I replaced the code manipulations in success callback, my code is working fine.
Thanks to #mccannf who pointed the problem in the above comments. :).
In jquery that is.
I would like something that works as the success-pararameter, but that is run when the function is called, rather than once I get the response.
sample (oajax is an extension of ajax for open auth)
$.oajax({
url: url,
jso_provider: "facebook", // Will match the config identifier
jso_scopes: false, // List of scopes (OPTIONAL)
dataType: 'json',
success: function(data) {
fbposts=data.data
//a bunch of code irellevant for the question
},//success done
error: function() {
console.log("ERROR Custom callback()");
}
})
};
Are you looking for .ajaxSend() ?
Attach a function to be executed before an Ajax request is sent.
This function (and .ajaxComplete et al) allow you to register callback functions that are called for the different phases of every AJAX request.
In a normal ajax function, you pass it as beforeSend:
$.ajax({
url: url,
dataType: 'json',
beforeSend: function(jqXHR, status){
// CODE HERE
},
success: function(data) {
fbposts=data.data
},
error: function() {
console.log("ERROR Custom callback()");
}
})
};
You'll have to check if oajax have this event too, but it probably do