Reputation: 4610
I'm trying to get the HTTP Response Code/Response Header from my AJAX request. Here's my original script:
$("#callContact1").click(function() {
$.ajax({
url: "https://www.server.com?type=makecall",
data: {},
type: "GET"
})
.then(function(data) {
$('#ajaxResponse').html(data).show();
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
console.log('ajaxError: ' + ajaxError);
//make alert visible
$('#ajaxResponse').html(ajaxError).show();
})
})
which is working fine. I've updated this to try and get the HTTP response code/header and view this in the console.log but I'm not seeing anything there. Here's my updated script:
$("#callContact1").click(function() {
console.log('starting call back request');
$.ajax({
url: "https://www.server.com?type=makecall",
data: {},
type: "GET"
})
.then(function(data) {
$('#ajaxResponse').html(data).show();
var httpStatus = (data.status);
var httpResponseCode = (data.getAllResponseHeaders);
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
console.log('ajaxError: ' + ajaxError);
//make alert visible
$('#ajaxResponse').html(ajaxError).show();
})
})
but I'm not getting anything in the console (the request is executed successfully though). I also noticed the output from the 2nd line of the updated script is also not appearing in the console either.
Upvotes: 1
Views: 1278
Reputation: 430
As you can find in jQuery's documentation for jQuery.ajax()
https://api.jquery.com/jQuery.ajax#jqXHR
you can use .done() and .fail() or using .then() which incorporates both, using two callback functions as parameters, the first for success and the second for fail.
So, you could use smt like this:
.then(function(data, status, xhr) {
$('#ajaxResponse').html(data).show();
var httpStatus = status;
var httpResponseCode = (xhr.status);
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
}, function(data, status, xhr) {
var ajaxError = 'There was an requesting the call back. HTTP Status: ' + status;
console.log('ajaxError: ' + ajaxError); //make alert visible
$('#ajaxResponse').html(ajaxError).show();
})
Upvotes: 0
Reputation: 406
Modify the above code to
.then(function(data,status,xhr) {
$('#ajaxResponse').html(data).show();
var httpStatus = status;
var httpResponseCode = (xhr.status);
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
})
Upvotes: 2