Defeating the popup blocker

I’m doing a WordPress site for a local business that involves a lot of custom PHP programming, which is interesting because I’ve never done PHP before. But heck, a language is a language and you can learn anything by googling these day.

So one of the things this site does is collect a bunch of information, and then submit it to a third party who then returns a URL for the specific payment page for that specific reservation, and you’re supposed to redirect the end user to that page to pay. I had that going where there was a WordPress shortcode that generated the form, and another WordPress shortcode on the destination page that did all that stuff, and then used a cheezy Javascript window.location=$url; thing to redirect it. That worked.

But the client had a look at it and didn’t like the fact that the end user ended up on a different site, and wanted it to pop up the payment page on a different tab or page. So I changed the Javascript to do window.open($url, "_blank");, but I found out that this causes every browser in the world to see that as a popup and block it. Asking end users to disable their popup blockers is probably a no-no.

Fortunately I discovered this post. He specifically talks about Chrome, but it also seems to work on Firefox, Mobile Safari, and even IE8. So I changed the form submit button into an ordinary button. Then I added a button click handler on it which quickly opens up a new window (if you delay it by single stepping with a Javascript debugger, it triggers the popup blocker) with some hopefully quick-loading bogus content, then making an AJAX call to get the URL, and in the “done” handler for the call, do a w.location = data.url; to redirect the new window to the correct url, and then does a “submit” on the form to take you to the correct new page on the original site. The Javascript code ended up looking like:

    
    /* When you submit the booking, make a popup window! */
    $('#info-form-fake-submit').on('click', function(eventObject) {
        var w = window.open(ajaxurl + "?action=pt_fake_page");
        $('body').addClass('loading');
        var $form = $('form.pt-form');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            datatype: 'json',
            data: $form.serialize() + '&action=pt_complete_reservation'
        }).done(function(data, textStatus, jqXHR) {
            if (data.status == 'good') {
                w.location = data.url;
                $form.submit();
            } else {
                alert(data.msg);
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            alert(textStatus + ': ' + errorThrown);
        }).always(function() {
            $('body').removeClass('loading');
        });
    });