skip to Main Content

In my page I have added function in jQuery which runs every 5 seconds. This function:

  1. Collects current records in a array currentRecords
  2. Makes an AJAX call and gets the new records in an array newRecords
  3. If the newRecords list contains a new record, this is added to the page.

The above logic is working right:

HTML:

<div class="pending-calls">
   <div class="call-record" id="id1">Record 1</div>
   <div class="call-record" id="id2">Record 2</div>
   <div class="call-record" id="id3">Record 3</div>
</div>

jQuery:

(function worker() {
    
    //Get current records
    var currentRecords = [];
    $('.call-record').each(function () {
        currentRecords.push($(this).prop('id'););
    });

    $.ajax({
        url: '#',
        dataType: "json",
        type: "POST",
        success: function (data) {              
            //Save records to an array and find the new record. If you find a new one, prepend it 'newRow' to the page.
            $('.pending-calls').prepend(newRow);
            //e.g <div class="call-record" id="id4">Record 4</div>
        },
        complete: function () {             
            setTimeout(worker, 5000);
        }
    });
})();

However, when a new record is found and it is added to the page, on the next loop the $('.call-record').. doesn’t catch it and as a result this new record <div class="call-record" id="id4">Record 4</div> is added endlessly in the page.

2

Answers


  1. Chosen as BEST ANSWER

    I found a walk around to my problem. I placed the array currentRecords outside of the function, so when the page is loaded it is filled once with the current records. After the ajax call, if I found a new record I added to the list.

    //Get current records
    var currentRecords = [];
    $('.call-record').each(function () {
        currentRecords.push($(this).prop('id'););
    });
    
    (function worker() {
        $.ajax({
            url: '#',
            dataType: "json",
            type: "POST",
            success: function (data) {              
                //Save records to an array and find the new record. If you find a new one, prepend 'newRow' to the page.
                if(newRowIsFound){
                    //add the id in the array
                    currentRecords.push(newRow.id);
               
                    //Add it to the page e.g <div class="call-record" id="id4">Record 4</div>
                    $('.pending-calls').prepend(newRow);
                }
            },
            complete: function () {             
                setTimeout(worker, 5000);
            }
        });
    })();
    

  2. The issue is that your initial selector doesn’t capture new elements added later. To solve this, use the .on() method to detect and add newly inserted call-record elements to currentRecords. This is the modified js.

    (function worker() {
        
        //Get current records
        var currentRecords = [];
        $('.call-record').each(function () {
            currentRecords.push($(this).prop('id'));
        });
    
        $.ajax({
            url: '#',
            dataType: "json",
            type: "POST",
            success: function (data) {              
                //Save records to an array and find the new record. If you find a new one, prepend it 'newRow' to the page.
                $('.pending-calls').prepend(newRow);
                //e.g <div class="call-record" id="id4">Record 4</div>
            },
            complete: function () {             
                setTimeout(worker, 5000);
            }
        });
    
        //Bind a function to the `.pending-calls` element that will execute whenever a new `.call-record` element is added to the page.
        $('.pending-calls').on('DOMNodeInserted', '.call-record', function () {
            //Add the new element to the `currentRecords` array.
            currentRecords.push($(this).prop('id'));
        });
    })();
    

    Hope this works for you.

    PS: Please Note that Using DOMNodeInserted may lead to performance problems when there are frequent additions of numerous elements to the DOM. Event handling might be excessive if real-time response to DOM changes isn’t necessary

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search