Enoch
Enoch

Reputation: 1011

Printing a div based on an AJAX request

The premise of what I am doing is simple in principle:

The user accesses the page.

  1. An AJAX call is made to a backend function that checks the database for documents to print

  2. If data is returned, a loop is ran, and within that loop another AJAX call is made to generate the receipts HTML.

  3. If the HTML is generated successfully, it is appended to an element (printDiv). This then forces the window.print function to run.

  4. Upon successful printing, a final call is made to update the database those documents were printed.

Problem: on FIRST access of the page. The calls are made, and when it eventually finds data it returns it. BUT on the first access it doesn't even get time to append the HTML to the document and but brings up the print dialogue. Once the dialogue is closed it then appends the HTML to the document.

CODE:

<script>
        var isActive = true;
        var isEmpty = true;
    
        $( document ).ready(function () {
            pollServer();
        });
        
        function pollServer()
        {
            if (isActive)
            {
                window.setTimeout(function () {
                    var isEmpty = true;
                    $.ajax({
                        url: "<?php echo site_url('CONTROLLER/unprinted');?>",
                        type: "POST",
                        dataType: "json",
                        success: function (result) {
                            for (var key in result) {
                               if (result.hasOwnProperty(key)) {
                                     isEmpty = false;
                                     getReceipt(result[key].id);
                               }
                            } 
                                                        
                            if( isEmpty == false ) {
                                console.log(isEmpty);
                                // chrome callback
                                var printCompleteCallback = function () {
                                    console.log('chrome');
                                }
                                
                                window.print();
                                if (window.onafterprint) { //check if browser supports window.onafterprint event handler (Firefox and IE)
                                    $(window).one("afterprint", printCompleteCallback);
                                    
                                    for (var key in result) {
                                       if (result.hasOwnProperty(key)) {
                                             updatePrintReceipt(result[key].id);
                                             console.log('print complete');
                                       }
                                    } 
                                }
                                else {
                                    setTimeout(printCompleteCallback, 0);
                                    
                                    // update db for those printed
                                    for (var key in result) {
                                       if (result.hasOwnProperty(key)) {
                                             updatePrintReceipt(result[key].id);
                                             console.log('other brower');
                                       }
                                    } 
                                    
                                }
                                    
                               $('#printDiv').html('');
                            }
                            
                             
                            //SUCCESS LOGIC
                            pollServer();
                            
                        },
                        error: function(xhr, status, error){
                             var errorMessage = xhr.status + ': ' + xhr.statusText
                             console.log('Error - ' + errorMessage);
                             pollServer();
                         }});
                }, 2500);
            }
        }
        
        function getReceipt(id){
            $.ajax({
                url: "<?php echo site_url('CONTROLLER/receipt_auto');?>" + "/" + id,
                type: "POST",
                success: function (result) {
                    $('#printDiv').append(result);
                },
                error: function(xhr, status, error){
                     var errorMessage = xhr.status + ': ' + xhr.statusText
                     console.log('Error - ' + errorMessage);
                }});
        }
        
        function updatePrintReceipt(id){
            $.ajax({
                url: "<?php echo site_url('CONTROLLER/receipt_update');?>" + "/" + id,
                type: "POST",
                success: function (result) {
                    console.log(result);
                },
                error: function(xhr, status, error){
                     var errorMessage = xhr.status + ': ' + xhr.statusText
                     console.log('Error - ' + errorMessage);
                 }});
        }


        
    </script>

Upvotes: 0

Views: 248

Answers (1)

parttimeturtle
parttimeturtle

Reputation: 1215

JQuery runs AJAX requests asynchronously by default (docs):

async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). 
If you need synchronous requests, set this option to false.

This means the call to window.print() is occurring before that getReceipt() ajax call finishes. Your interior AJAX calls need to be run synchronously so that the outside AJAX call can't proceed until they finish.

Upvotes: 1

Related Questions