window.open() works different on AJAX success

T1000 picture T1000 · Apr 19, 2012 · Viewed 38.1k times · Source

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

Answer

Rick Hoving picture Rick Hoving · Apr 19, 2012

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.