Search code examples
performancejquerylong-polling

Polling jQuery ajax for each. Check if element does not exist, if so prepend to div


I have a div #notification-data which on $(document).ready gets populated with multiple <li></li> from $.post.

The $.post then gets called setTimeout(poll_n,9000); so data is up-to-date.

So im not updating all the data every time, I would like to do check if the <li></li> already exists in #notification-data, if it does not exist then I would like to prepend() it to #notification-data.

The data comes in the form of:

<li id="new_notification_1" class="seen_0 li_notification">blah</li>
<li id="new_notification_2" class="seen_0 li_notification">bleh</li>

As an extra question, is this the correct way of long polling?

Here is my code:

function poll_n(){
        $.post('<?php echo $siteUrl ?>notifications.php?x=' + (new Date()).getTime() +'', function(data) {

            $(data).find(".li_notification").each(function () {

                    var li_id = $(this).attr('id');
                    if ($(li_id).closest('#notification-data').length) {
                        //do nothing
                    } else {
                        $('#notification-data').append(??not_sure_what_goes_here??);  // process results here           
                    }

            });

            setTimeout(poll_n,9000);
        }); 
    }

EDIT - After answer I have now got this but it does not work (I get nothing in the console).

success: function(data){

    $(data).find(".li_notification").each(function() {              
            var id = $(this).attr('id'),
                notification = $('#notification-data');
                console.log(id);
                console.log('hello');
            if (notification.find('#' + id).length === 0) {
                // notification doesn't exists yet then lets prepend it
                notification.prepend('#' + id);
            }

    });

},

Solution

  • You can try this:

    function poll_n() {
    $.ajax({
        type: 'POST',
        url: 'your url',
        success: function(data){
            var notification = $('#notification-data');
            $.each($(data), function(){
                var id = this.id;
                if (notification.find('#' + id).length === 0) {
                    // notification doesn't exists yet then lets prepend it
                    notification.prepend(this);
                }
            });
        },
        complete: function(jqXHR, status) {
            if (status === 'success') {
                setTimeout(poll_n, 9000);
            }
        }
    });
    }
    

    You must call poll_n() again after the request has been completed.