Jquery window.open in "Success" in ajax is being blocked

Asked

Viewed 902 times

0

I would like when saving an input and updating the div with the new information, in the return message "Success" ajax, to also print the div. Example

success :  function(response){                  
 $("#containerResultado").html(response);
 var divToPrint = document.getElementById('divresultado');
            var popupWin = window.open('', '_blank', 'width=800,height=600');
            popupWin.document.open();
            popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
            popupWin.document.close();
}

1 answer

4


Usually browsers block the method window.open when it is not a direct action of the user. One solution would be to open the window before calling AJAX and after AJAX’s response manipulated it, it would look something like this:

var popupWin = window.open('', '_blank', 'width=800,height=600');

$.ajax({
    type: "...",
    url: ...,
    data: ...,
    contentType: "...",
    dataType: "...",
    success: function(response){                  
      $("#containerResultado").html(response);
      var divToPrint = document.getElementById('divresultado');
      popupWin.document.open();
      popupWin.document.write('<html><body onload="window.print()">' + 
      divToPrint.innerHTML + '</html>');
      popupWin.document.close();
},
    error: function (response) {
      popupWin.close();
    }
});
  • Thanks for the feedback. I had the idea to do with iframe that for my case works even better: <iframe id="printf" name="printf"></iframe> var newWin = window.frames["printf"];&#xA;newWin.document.write('<body onload="window.print()">dddd</body>');&#xA;newWin.document.close();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.