Search code examples
javascriptjqueryajaxnew-window

Writing html to a new window with javascript


I have been doing some research on opening a new window and writting HTML to it with jQuery/JavaScript and it seems like the proper way to do it is to:

Create a variable for the new window

var w = window.open();

Insert the new data and work the variable

$(w.document.body).html(data);

And to me, that makes complete sense. however when i try to incorporate this into my script ("data" being the holder for the HTML) it does not open a new window... unless I'm just missing something simple which as far as I can tell it looks great...

function newmore(str) {
    var identifier = 4;
    //get the history
    $.post("ajaxQuery.php", {
        identifier : identifier,
        vanid : str
    },
    //ajax query 
    function(data) {
        //response is here
        var w = window.open();
        $(w.document.body).html(data);
    });//end ajax                
}

Any ideas?

P.S. there seems to be no errors in the console


Solution

  • Your new window is probably being blocked by the popup blocker built into most browsers. If you create the new window as a direct result of a user action (key, click), then the browser usually will not block it. But, if you wait until sometime later (like after an ajax call completes), then it will get blocked and that is probably what is happening in your case.

    So, the fix is usually to create the window immediately in direct response to the user event (don't wait until the ajax call completes), keep the window handle in a variable and then put the content in the window later after your ajax call completes.

    function newmore(str){
        var identifier = 4;
        // create window immediately so it won't be blocked by popup blocker
        var w = window.open();
        //get the history
        $.post("ajaxQuery.php", {
            identifier : identifier,
            vanid : str
        },
        //ajax query 
        function(data) {
            //response is here
            $(w.document.body).html(data);
    
        });//end ajax                
    
    }