It will be more easy for me to explain the problem if I just show you that example -> http://jsfiddle.net/RU2SM/
As you can see there are 2 buttons, one called'AJAX' and one called 'Direct'... So if you click on 'Direct' it opens window (new tab on Chrome) but if I try to make window.open() on AJAX success handler, it doesn't work same way.
I'm sure that the problem is from AJAX but I have no idea how to fix it.
Will appreciate any good ideas.
Thanks
You can check when exactly it returns "success" : // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { ... // If not modified if ( status === 304 ) { statusText = "notmodified"; ... // If we have data } else { try { ...
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
Yes, it is deprecated in jQuery 1.8 onwards. You should use . done() and use . fail() to catch the errors.
AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.
This works like a charm:
// Direct window.open()
$('#btnDirect').on('click',function(){
window.open('http://google.com')
})
var success = false; //NOTE THIS
// AJAX window.open()
$('#btnAJAX').on("click", function(){
$.ajax({
url: "/user/login/",
context: document.body,
async:false, //NOTE THIS
success: function(){ //THIS ALSO CHANGED
success = true
}
});
if(success){ //AND THIS CHANGED
window.open('http://google.com')
}
})
What this does is when the Ajax call is success it sets the variable success to true.
The async:false
propperty makes sure that the if statement is fired after the Ajax call is completed.
So the window.open is fired in the same circumstances as your direct link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With