how to get jquery ajax status code - javascript

I want to know that how can we get ajax status code in jquery.
I have this ajax block:
$.ajax{
type: "GET",
url: "keyword_mapping.html",
data:"ajax=yes&sf="+status_flag,
success: callback.success,
complete: rollup_filters(),
failure: function(){
alert("Failure");
}
}
Now in above code, in case of failure, how can i get ajax status code and some description of that status code ??

You want to use the error option to capture this. For example:
error: function (jqXHR, textStatus, errorThrown)
// Your handler here...
}
You can then use the jqXHR object to retrieve information about the failure.
From the documentation:
For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
abort()

First, you have a few syntax errors. The above is a method call, so it needs to follow $.ajax({ ... }); (with parenthesis).
Secondly, you want to supply the error property as part of the object, not failure (see docs for more information).
Third, when you do bind to an error, you are supplied three parameters: jqHXR, textState, errorThrow. These arguments will supply you the details of a failed AJAX call. (More specifically, try jqXHR.status)
Alternatively, you can bind to the $.ajaxError function as well.
Update To keep this more up-to-date, you should now be following the Deferred API (as of jQuery 1.5), which would make binding to an error look something like the following:
$.ajax({ /* options */ })
.done(function( data, textStatus, jqXHR ){
// here you bind to a successful execution.
.fail(function( jqXHR, textStatus, errorThrown ){
// Here you can catch if something went wrong with the AJAX call.
})
.always(function(){
// here you can execute code after both (or either) of
// the above callbacks have executed.
});

Change your failure callback to
error:function (xhr, options, error){
alert(xhr.status);
alert(error);
}

There is nothing like failure in ajax settings. Replace failure by error and you get 3 arguments in the error callback. First argument is the xhr object which has a status property in it.
$.ajax{
type: "GET",
url: "keyword_mapping.html",
data:"ajax=yes&sf="+status_flag,
success: callback.success;
complete: rollup_filters(),
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
}
}

Related

Wrapped $.ajax issue

$.ajax is wrapped into new 'get' function.
If there is only one 'get' invoke in js file, it is fine.
But 2 calls in row fail.
More precise,
first call fails with "Uncaught ReferenceError: process is not defined",
second one is successful, BUT in success function it has data for first 'get' invoke.
As I can guess, there is some issue with 'this'/context. Could you explain it to me?
(function() {
"use strict";
function get(url, success, error) {
$.ajax({
type: "GET",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'process',
url: url,
success: success,
error: error
});
}
get('XXX',
function(data, textStatus, jqXHR) {
console.log("SUCCESS PING 1");
console.log(data);
},
function(jqXHR, textStatus, errorThrown) {
console.log("ERROR PIND 1");
});
get('YYY',
function(data, textStatus, jqXHR) {
console.log("SUCCESS PING 2");
console.log(data);
},
function(jqXHR, textStatus, errorThrown) {
console.log("ERROR PING 2");
});
})();
/*
===========================================
===============console=====================
===========================================
1. ERROR PIND WAR
2. Uncaught ReferenceError: process is not defined
at db?callback=process&_=1485184752755:1
3. SUCCESS PING DB
4. Object {data for first call here}
*/
First of all, It's better do NOT specify a custom callback name ('jsonpCallback' parameter)
http://api.jquery.com/jQuery.ajax/
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.
The thing is, that jQuery creates global function in window object with specified name and later remove it.
I didn't manage to get full picture of what going on inside jQuery library, but
the issue is definitely caused by fact that it tries to call function that just has been removed.
Removing jsonpCallback param resolve an issue

Getting "parsererror" in jquery ajax

Below is my AJAX code. Here I'm hitting a service with one value. The service is getting called successfully, but it is not going into the success method. It is going into the error method only. In the error method it is giving parsererror and message: Unexpected token S
$.ajax({
type: 'GET',
url: 'http://domin.com:9000/ramsweb/rest/DetailRest/addOrderContacts/123456/' + customerId,
success: function (data, status, xhr) {
console.log(data);
$("#loadingSpinner").hide();
},
error: function (jqXhr, textStatus, errorMessage) {
$('.ErrorMsg').html('<h5>An error has occurred</h5>');
},
fail: function (data) {
$('.ErrorMsg').html('<h5>data loading failed</h5>');
}
});
jQuery AJAX functions by default will try to detect the type of response depending on other pieces of data in your request and response (headers etc.)
Most likely, your endpoint serves it as JSON thus telling jQuery to internally do a JSON.parse. However, your endpoint may be serving an error page instead of JSON which can cause parse errors like this.

jQuery nested within .get request won't execute

I have the following jQuery get request, which returns html text under the key name "data":
$(".article").click(function() {
$.get("<%= click_path %>", function(data) {
$(".article").html(data);
});
});
All the code executes except the line $(".article").html(data);. In fact, any jquery code I put inside the get request fails to execute, even though it all works fine if I move it outside the get request. Does anyone see anything wrong with my syntax?
jQuery's $.get method is an alias to $.ajax with an assumed HTTP request method of GET and without the ability to specify many options. You give it a URL and a function to run on successfully retrieving that URL. It tries to GET that URL and, if it can, the success function will run. If it can't, or if something is wrong with the response data, it fails silently and will not run the given function.
That being the case, I would assume your request is failing somewhere.
You need to look in the developer's console for errors and to inspect the request.
You can also change your code to use $.ajax and pass in the options, along with your current params, an error method. If the error method is called, you'll receive as params the jqXHR instance, a string textStatus, and a string errorThrown. Pass these into console.log and look at them for clues as to what is wrong as well.
$(".article").click(function() {
$.ajax({
url: "<%= click_path %>",
success: function(data) {
$(".article").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
}
});
});
Chances are, your ajax request fails to execute and as result, your jQuery code inside the callback never runs.
Run the following instead and see if an error is alerted:
var jqxhr = $.get( "<%= click_path %>", function() {
alert( "success" );
}
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});

calling Web service via ajax - proper response in my error callback

I am trying to get some data from a web service via ajax using the below function,
but I get this response message:
{"readyState":4, "status":200, "statusText":"load"}
The WS is supposed to return an array of json and, if I look in my chrome dev tool
in network tab -> Response, I actually get the proper array of json.
Question:
Why am I getting the result in my errorFunction callback?
function callWebService(wsUrl, params, successFunction, errorFunction) {
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Methods', ' GET');
xhr.setRequestHeader("Content-Type",
"application/json; charset=utf-8");
xhr.setRequestHeader("Accept", "application/json");
},
type: "GET",
url: wsUrl,
data: params,
dataType: "json",
contentType: "application/json",
success: successFunction,
error: errorFunction
});
}
Here is my console.log when I use this error function function(jqXHR, status, error)
*Resource interpreted as Script but transferred with MIME type text/html: "http://www.myweb.it/services/service.php?callback=jQu…y21109160579217132181_1405523828314&codice_istituto=150201&_=1405523828315". jquery.js:8691send jquery.js:8691jQuery.extend.ajax jquery.js:8152callWebService global.js:5(anonymous function) index.js:49jQuery.event.dispatch jquery.js:4409elemData.handle jquery.js:4095
an error occurred: index.js:52
parsererror index.js:53
Error {stack: (...), message: "jQuery21109160579217132181_1405523828314 was not called"}message: "jQuery21109160579217132181_1405523828314 was not called"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: d index.js:54
readyState: 4 index.js:56
jqXHR.status: 200 index.js:57
jqXHR.statusText:load index.js:58
jqXHR.responseText: undefined*
You're seeing the error callback fired because there's something wrong with your AJAX request, and it's not returning successfully. Identifying why this happens is another matter.
The first argument jQuery passes to your error callback is the jqXHR object:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
This is different from the success callback, which begins with the data returned:
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
jqXHR is a superset of the xmlHttpRequest object JavaScript returns. Inside it, you're seeing readyState of 4, which simply means "done", and status of 200 means a successful request. So, at least you know you're probably pointing your request at the right URL.
You should be able to get other information from your jqXHR object which might help you identify the cause of the error. From the docs:
For backward compatibility with XMLHttpRequest, a jqXHR object will
expose the following properties and methods:
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
statusCode()
abort()
That object you're seeing is an XMLHTTPResponse; a representation of the actual AJAX request. You're getting it passed into your error handler because that's the first argument of jQuery's ajax error callback.
Figuring out why it's calling the error callback and not the success callback is harder. That statusText suggests that your server returned the string 'load' - is that a possibility? Another common problem is if your data isn't actually valid JSON. JSON's quite a picky format; if you're producing it yourself, you might have invalid whitespace or the wrong kind of quotes (or completely missing quotes). Check your data with a tool like JSONLint and make sure it's valid, and make sure that your server is only returning JSON - nothing else in the response body.
Just a work around
1. remove dataType:'json'
2. parse json in success function call
data = $.parseJSON(data);

Resend an ajax request if case of error or error code

I a javascript function which sends an ajax request. Note that the server might return an error even if "everything seems to be ok" which means that there might be an error information in the handler of success:
function sendAjaxRequest(){
$.ajax({
type: "GET",
url: "/123",
success: function(data){
//there might and might not an error in data
if(data.error_exists){
retryIfError(data);
} else{
//everything is ok for sure
}
},
error: function(xhr, textStatus, errorThrown){
//there is the error for sure
retryIfError(xhr);
}
});
}
function retryIfError(data){
var error = data.error_list # the array of error messages
// ... what should I do further?
}
The reason is that success: function(data) might have an error is that the server uses begin ... rescue operators to suppress them. Is that the right approach?
The second question:
So the goal is to send sendAjaxRequest() until there are no errors anymore. How do I do that? Of course, I want also restrict the amount of sending sendAjaxRequest() requests, but I think it will be trivial and I'll take care of it by myself.
What about calling the function again? you can add a counter as well.
error: function(xhr, textStatus, errorThrown){
if(i<3)
sendAjaxRequest(i++);
}
And use.
var i=0;

Categories

Resources