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

0

I would like when saving an input and updating the div with the new information, in the return message "success" of ajax, also make the impression of 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();
}
    
asked by anonymous 06.06.2017 / 16:15

1 answer

3

Generally, browsers block the window.open method when it is not a direct action of the user. One solution would be to open the window before calling AJAX and after the AJAX response manipulates 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();
    }
});
    
06.06.2017 / 16:27