-1

I have an AJAX function which takes some time to complete. When it's done I want to open a new tab with the result. To do so I've came up with three options:

  1. Use window.open() from the AJAX-call
  2. Use window.open() in the javascript function/event trigger.
  3. Use window.open() in a setTimeout-function within the javascript function/event trigger.

The problem is this has to work with all major browsers (IE, Chrome, Firefox and Safari) and option 3 should do the trick but is has unwanted side effects:

  1. In Chrome the window is not opened in a new tab but as a pop up.
  2. In Safari the internal popup prevention is activated; resulting in not opening the popup. (source)

Now I figured to use setTimeout() as a piece of procedural code and ending up with some like:

$('.selector').click(function() { 
  doAjaxCall();
  setTimeout(function(){ }, 150);
  window.open(...);
});

Well, this works for Safari but Chrome and FireFox seem to ignore the setTimeout() and continue directly to the window.open(). Herein lies my problem; the data that has to be used isn't always up to date when window.open() gets called.

So, here I am. Back to basics. Figured out what the symptoms are, knowing the downsides of my explored scenario's and ended up with a something like this:

$('.selector').click(function() { 
  doAjaxCall();
  for(i = 0; i <= 100000000; i++) { 
    // procedural and time consuming so doAjaxCall has enough time to complete 
  }
  window.open(...);
});

In my case I'm stuck to xajax for the ajax-handling, so I can't use jQuery's ajax solution.

Any suggestions on how to improve this? Resulting in a solution where all major browsers open the popup when the ajax-function has completed?

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129

1 Answers1

1

First of all, the browsers don't ignore the setTimeout function, but the execution doesn't stop and wait for a setTimeout completion, but will continue it's execution and wait for the timeout to complete in order to execute the method passed as argument to setTimeout method.

But you don't need to simulate the sleep method from php in order to achieve what you want. The ajax call has a success event which you can attach an event handler on. Open your new tab when the success event occurs. Otherwise, you wont be able to know exactly when the ajax request ended. If you can't use the jQUery's ajax, you can create an 'old-school' ajax request, like here

Also, opening a new window is not the best solution, because most browsers have popup blockers.

Valentin S.
  • 504
  • 2
  • 10