window.open() works different on AJAX success
as an addition it is also worth mentioning that using async: false and then calling window.open works in chrome and firefox but can cause trouble in safari... it doesn't even give an info that a popup was blocked
Better way implement any logic after success of ajax call, there is an event fired on every ajax call execution i.e. $.ajax.Request.done and $.ajax.Request.fail. $.ajax.Request.done(function(){ if(success){ // Implement logic } });
The issue is that browsers will often block window.open
s unless they're called in direct response to a user action. That's why your click handler works (a click is a user action) but your AJAX handler doesn't.
One solution is to open the window during the initial click action, then update its location on AJAX success (or close it again on AJAX failure).
Otherwise you'll have to get the user to explicitly allow popups from your domain in their browser.
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.