Reputation: 57
Can anyone please tell me why I am getting readyState as 1 and status as undefined for the following
$(document).ready(function(){
$('.delsub').on('submit', function (event){
event.preventDefault();
var xhr = $.ajax({
url: 'delRept.php',
type: 'POST',
data: "&delsub=delsub",
success: function(d){
console.log(d);
}
});
console.log(xhr.readyState);
console.log(xhr.status);
});
});
Thank you
Upvotes: 0
Views: 489
Reputation: 74738
As ajax is asynchronous call, it doesn't wait for the result instead it jumps to next line whatever is written there. So in your case when you call your ajax on submit
method:
var xhr = $.ajax({}); // here you assign the ajax to a var xhr
and right after that call you have used to output the state to the console with:
console.log(xhr.readyState); // logs the state of the ajax
So in your case issue is ajax is async call so whenever ajax code is assigned to xhr
right after that you are logging the state. so everytime it will log 1
.
If you go through the documentation you can see that there is a complete:fn
callback, you can use it:
$('.delsub').on('submit', function (event){
event.preventDefault();
var xhr = $.ajax({
url: 'delRept.php',
type: 'POST',
data: "&delsub=delsub",
success: function(d){
console.log(d);
},
complete:function(xhr){
console.log(xhr.readyState);
console.log(xhr.status);
}
});
});
or if you want to do some operations on different statuses then you can use statusCode:{}
:
$('.delsub').on('submit', function (event){
event.preventDefault();
var xhr = $.ajax({
url: 'delRept.php',
type: 'POST',
data: "&delsub=delsub",
statusCode:{
200:function(){
console.log(xhr.readyState);
console.log(xhr.status);
alert('200');
},
304:function(){
console.log(xhr.readyState);
console.log(xhr.status);
alert('304');
}
},
success: function(d){
console.log(d);
}
});
});
Upvotes: 2
Reputation: 337620
The issue is because the request is asynchronous, and you're logging readyState before the request completes, hence it's always 1
. If you need to check those values you need to put them in the success
callback so that they execute after the request has completed:
var xhr = $.ajax({
url: 'delRept.php',
type: 'POST',
data: "&delsub=delsub",
success: function(d){
console.log(d);
console.log(xhr.readyState);
console.log(xhr.status);
}
});
Upvotes: 1