Question

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

Was it helpful?

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                

}

OTHER TIPS

Try instead:

var w = window.open();
w.document.write(data);

The "innerHTML" property of the document object (which is what jQuery's .html() uses) represents the HTML document, which a new window doesn't have. Even if it did, putting a complete document inside an HTML document doesn't really make sense. It's a freshly-created document, so you can just write to it.

This peace of code will work:

var data = "<h1>Test</h1>";
var w = window.open("", "mywindow1", "width=350,height=150");
$(w.document.body).html(data);

You have to inform some parameters when opening new windows.

But, if possible, I'd hardly recommend that you use another way like, jquery UI or Twitter Bootstrap for doing that, so you will not be using pop-ups.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top