Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Reload page after form submit with target="_blank"

I'm trying to achive the following:
On page A we have an access restricted Link to page B. The access restriction is handled on the server side in PHP.
When a user clicks on this link to page B we display a modal dialogue on page A (via javascript) with a form, having the link's href (B) as the action. (To give the user an immediate feedback. The fallback is to redirect him to a login form that redirects him to the site he wants to access.) This system works quite well.

But now comes my question:
We have access restricted links that should be opened in a new window.
Now if I use target="_blank" on the form the user stays logged out on the page he came from (A), that is still open in the background.
Is there a way to reload the page (A, in the background) right after the form has been submitted to the new window (B)?

My first idea was to use window.location.reload(); in the submit handler on page A.
This didn't work in chrome and from what I understand could create a race condition.

Another idea would be to log the user in via an ajax call and open a new window through javascript. Is there a way to do this without having to deal with pop-up blockers?


I implemented the idea of lostsource (see below) with one slight addition.
As I need to reload only once, the timer of setInterval can be stopped if the cookie changed.

var ri=setInterval(function() {  
    if(oldCookie != document.cookie) {  
        // assuming a login happened, reload page  
        clearInterval(ri);  
        window.location.reload();  
    }  
},1000); // check every second

I still love the idea. stackoverflow is awsome!

like image 684
baru Avatar asked May 03 '26 06:05

baru


1 Answers

Assuming you're storing PHP session information inside a cookie, you might be able to monitor your document.cookie for changes.

Before submitting the form store the value of the current cookie and monitor it for changes with a timer:

form.onsubmit = function() {
     var oldCookie = document.cookie;

     var cookiePoll = setInterval(function() {
         if(oldCookie != document.cookie) {
             // stop polling
             clearInterval(cookiePoll);

             // assuming a login happened, reload page
             window.location.reload();
         }
     },1000); // check every second
}
like image 56
lostsource Avatar answered May 04 '26 19:05

lostsource



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!