javascript: Print text that is received via ajax

user984003 picture user984003 · Jun 27, 2013 · Viewed 16.7k times · Source

This is what I want to do:

  1. User clicks print button;
  2. This calls function, which does ajax call to get the text to be printed;
  3. A new window is opened and the text is written to this.

The window and print is handled like this:

 my_text = "hello";

 newWin= window.open();
 newWin.document.write(my_text);
 newWin.document.close();
 newWin.focus();
 newWin.print();
 newWin.close();

This works fine. My issue is how to get my_text. I have tried to put the above code inside an ajax call:

$.ajax({
        type: "GET", url: the_url, data: {},
        success: function(data){
             newWin= window.open();
             newWin.document.write(data);
             newWin.document.close();
             newWin.focus();
             newWin.print();
             newWin.close();
        }
        ,error: function() {
        } 
     }); 

However, this causes the new window to be seen as a pop-up and it's caught by the pop-up blocker. If I choose to see the pop-up message then it has correctly filled in the text. I tried opening the window first, but then nothing gets written to it.

Answer

Sean picture Sean · Jun 27, 2013

Try moving the line:

newWin = window.open();

before the $.ajax(...) call. Your window will open immediately, and when the ajax call completes, your success handler should be able to write to it. You would end up with something like:

var newWin = window.open();
$.ajax({
    type: "GET", url: the_url, data: {},
    success: function(data){
        newWin.document.write(data);
        newWin.document.close();
        newWin.focus();
        newWin.print();
        newWin.close();
    }
    ,error: function() {
    }
});

Simplified version using setTimeout for "proof on concept" purposes.

<html>
<head>
<script>
function openWindow() {
  var win = window.open("about:blank", "", "width=800,height=600");
  setTimeout(function() {
    win.document.write("Hello world!");
    win.document.close();
  }, 1000)
}
</script>
</head>
<body>

<button type="button" onclick="openWindow()">Click me</button>

</body>
</html>