I want to check if a page returns the status code 401. Is this possible?
Here is my try, but it only returns 0.
$.ajax({
url: \"http://my-ip/tes
this is possible with jQuery $.ajax()
method
$.ajax(serverUrl, {
type: OutageViewModel.Id() == 0 ? "POST" : "PUT",
data: dataToSave,
statusCode: {
200: function (response) {
alert('1');
AfterSavedAll();
},
201: function (response) {
alert('1');
AfterSavedAll();
},
400: function (response) {
alert('1');
bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
},
404: function (response) {
alert('1');
bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
}
}, success: function () {
alert('1');
},
});
Test in WAMP SERVER apache2
abrir el httpd.conf y agregar esto:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
enable the next module on apache headers_module
restart all services
Use the error callback.
For example:
jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
alert(xhr.status); }
});
Will alert 404
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});
I encapsulate the jQuery Ajax to a method:
var http_util = function (type, url, params, success_handler, error_handler, base_url) {
if(base_url) {
url = base_url + url;
}
var success = arguments[3]?arguments[3]:function(){};
var error = arguments[4]?arguments[4]:function(){};
$.ajax({
type: type,
url: url,
dataType: 'json',
data: params,
success: function (data, textStatus, xhr) {
if(textStatus === 'success'){
success(xhr.code, data); // there returns the status code
}
},
error: function (xhr, error_text, statusText) {
error(xhr.code, xhr); // there returns the status code
}
})
}
Usage:
http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
console(status_code, data)
}, function(status_code, err){
console(status_code, err)
})
I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.
The best way to combat this is to call the .always
chain method and do a bit of cleaning up. Here is my code.
$.ajax({
...
}).always(function(data, textStatus, xhr) {
var responseCode = null;
if (textStatus === "error") {
// data variable is actually xhr
responseCode = data.status;
if (data.responseText) {
try {
data = JSON.parse(data.responseText);
} catch (e) {
// Ignore
}
}
} else {
responseCode = xhr.status;
}
console.log("Response code", responseCode);
console.log("JSON Data", data);
});