0

I have this script from plugin i used "DW Notifications", the problem i'm facing is the ajax auto check for new notifications working always on the front end and this makes my site loading too much.

So, How can i check the ajax only when the notification list is open?

I'm newbie with WordPress, and i searched more time to fix that problem but i failed.

jQuery(document).ready(function($){
    var tempPopup;
    var time = dwnotif.dwnotif_current_time;
    var old_time = time;

    if(!$('#dw-notifications').length){
        return;
    }

    var change_numer = 0;
    var minTimeRequest = 2000;
    var maxTimeRequest = 30000;
    var currentTimeRequest = 10000;
    var timeoutPopup = 15000;


    autoCheck();

    function changeTimeRequest(changed = false){

        if(changed){
            currentTimeRequest = currentTimeRequest/2;
        }else{
            change_numer++;
            if(change_numer<5){
                return false;
            }
            currentTimeRequest = currentTimeRequest*2;
            change_numer = 0;
        }

        if(currentTimeRequest<minTimeRequest){
            currentTimeRequest = minTimeRequest;
        }

        if(currentTimeRequest>maxTimeRequest){
            currentTimeRequest = maxTimeRequest;
        }
    }



    function autoCheck(changed = false){
        changeTimeRequest(changed);
        changeTimeItem(time);
        changeReadItem();
        setTimeout(checkNotifications, currentTimeRequest);
    }

    function checkNotifications(){
        $.ajax({
            url: dwnotif.dwnotif_ajax_url,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'dwnotif_check_notifications',
                nonce: dwnotif.dwnotif_nonce,
                time: time,
            },
            success: function( data ) {

                var changed = false;
                if (data.success) {
                    if(data.result.newest_notifications){
                        $('#dw-notifications .list-notification').prepend(data.result.newest_notifications);

                        if(data.result.count_unchecked){
                            $('#dw-notifications').find('.dw-notification-btn').addClass('has-notification');
                            $('#dw-notifications').find('.notif-count-unchecked').text(data.result.count_unchecked);
                        }

                        if(data.result.newest_notifications_popup){
                            addPopup(data.result.newest_notifications_popup);
                        }

                        changed = true;
                    }

                    /*if(data.result.length>0){
                        for(var i=0;i<data.result.length;i++){
                            $('.dw-notifications._' + data.result[i].id).find('.list-notification').html(data.result[i].html);
                            if(data.result[i].new){
                                addPopup(data.result[i].id, data.result[i].new);
                                changed = true;
                            }
                            if(data.result[i].count_unchecked){
                                addHasNotifications(data.result[i].id, data.result[i].count_unchecked);
                            }
                        }
                    }*/
                    time = data.time;
                }
                autoCheck(changed);
            },
            error: function (request, status, error) {
                autoCheck(false);
            }
        });
    }

    function changeTimeItem(){
        $('.dw-notifications .list-notification').find('li').each(function(e){
            var diff= dw_human_time_diff($(this).data('time'), time);
            $(this).find('.notif-time').text(diff);
        });
    }

    function changeReadItem(){
        //change read all
        var markReadAll = getCookie('dw_read_all_time');
        if(markReadAll){
            // all read
            $('#dw-notifications .list-notification').find('.unread').each(function(){
                var item_time = $(this).data('time');
                if(item_time <= markReadAll){
                    $(this).removeClass('unread').addClass('read');
                }
            });
        }

        //change read item
        var readList = getCookie('dw_read_list');
        if(readList){
            var listItems = readList.split(",");
            for(var i = 0; i < listItems.length; i++){
                $('#dw-notifications .list-notification').find('#dw-notif-' + listItems[i] + '.unread').removeClass('unread').addClass('read');
            }
        }

        //change has notification
        var checkedTime = getCookie('dw_checked_time');
        if(checkedTime && checkedTime >= old_time){
            $('#dw-notifications .dw-notification-btn').removeClass('has-notification');
        }
        old_time = time;
    }

    function addPopup(itemHtml){
        var popup_id = '#dw-notif-popup';
        if($(popup_id).length){

            $(popup_id).addClass('open');

            var item = $(itemHtml);
            //close popup notify
            item.on('click', function(){
                $(this).closest('.dw-notif-popup').remove();
            });
            $(popup_id +' ul').append(item);

            clearTimeout(tempPopup);
            tempPopup = setTimeout( function(){ $(popup_id).removeClass('open'); $(popup_id +' ul').html('');}, timeoutPopup);
        }

    }

    //user checked
    $('.dw-notification-btn').on('click', function(){

        $(this).removeClass('has-notification');

        var notifications = $(this).closest('.dw-notifications');

        if(notifications.hasClass('open')){
            notifications.removeClass('open');
        }else{
            notifications.addClass('open');

            if(!dwnotif.dwnotif_is_user_logged_in){
                //if user not logged => return false
                return false;
            }

            $.ajax({
                url: dwnotif.dwnotif_ajax_url,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'dwnotif_mark_user_checked',
                    nonce: dwnotif.dwnotif_nonce,
                },
                success: function( data ) {
                    // if (data.success) {
                    //  //read all
                    //  notifications.find('.unread').addClass('read').removeClass('unread');
                    // }
                },
                error: function (request, status, error) {

                }
            });
        }

    });

    //mark item read
    $(document).on('click', '.list-notification .unread', function (e) {
        $(this).removeClass('unread').addClass('read');
    }); 

    //mark all as read
    $('.dw-notif-mark-all-read').on('click', function(){
        var notifications = $(this).closest('.dw-notifications');
        var id = notifications.data('id');

        $.ajax({
            url: dwnotif.dwnotif_ajax_url,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'dwnotif_mark_all_as_read',
                nonce: dwnotif.dwnotif_nonce,
                id: id,
            },
            success: function( data ) {
                if (data.success) {
                    //read all
                    notifications.find('.unread').addClass('read').removeClass('unread');
                }
            },
            error: function (request, status, error) {

            }
        });
    });

    $(document).on('click', function (e) {
        $('.dw-notifications').removeClass('open');
    });
    $(document).on('click', '.dw-notifications', function (e) {
      e.stopPropagation();
    });
});

//custom time diff
function dw_human_time_diff( from = false, to = false) {
    if ( !from || !to ) {
        return false;
    }
    var  constants =dwnotif.dwnotif_constants;

    var diff = parseInt(Math.abs( to - from ));

    if ( diff < constants.HOUR_IN_SECONDS ) {
        var mins = Math.round( diff / constants.MINUTE_IN_SECONDS );
        if ( mins <= 1 )
            mins = 1;
        /* translators: Time difference between two dates, in minutes (min=minute). 1: Number of minutes */
        var since = mins==1? mins +' min' : mins +' mins';
    }  else if ( diff < constants.DAY_IN_SECONDS && diff >= constants.HOUR_IN_SECONDS ) {
        var hours = Math.round( diff / constants.HOUR_IN_SECONDS );
        if ( hours <= 1 )
            hours = 1;
        /* translators: Time difference between two dates, in hours. 1: Number of hours */
        var since = hours==1? hours +' hour' : hours +' hours';
    }  else if ( diff < constants.WEEK_IN_SECONDS && diff >= constants.DAY_IN_SECONDS ) {
        var days = Math.round( diff / constants.DAY_IN_SECONDS );
        if ( days <= 1 )
            days = 1;
        /* translators: Time difference between two dates, in days. 1: Number of days */
        var since = days==1? days +' day' : days +' days';
    }  else if ( diff < constants.MONTH_IN_SECONDS && diff >= constants.WEEK_IN_SECONDS ) {
        var weeks = Math.round( diff / constants.WEEK_IN_SECONDS );
        if ( weeks <= 1 )
            weeks = 1;
        /* translators: Time difference between two dates, in weeks. 1: Number of weeks */
        var since = weeks==1? weeks +' week' : weeks +' weeks';
    }  else if ( diff < constants.YEAR_IN_SECONDS && diff >= constants.MONTH_IN_SECONDS ) {
        var months = Math.round( diff / constants.MONTH_IN_SECONDS );
        if ( months <= 1 )
            months = 1;
        /* translators: Time difference between two dates, in months. 1: Number of months */
        var since = months==1? months +' month' : months +' months';
    }  else if ( diff >= constants.YEAR_IN_SECONDS ) {
        var years = Math.round( diff / constants.YEAR_IN_SECONDS );
        if ( years <= 1 )
            years = 1;
        /* translators: Time difference between two dates, in years. 1: Number of years */
        var since = years==1? years +' year' : years +' years';
    }
    return since;
}


function setCookie(cname, cvalue, extimes) {
    var d = new Date();
    d.setTime(d.getTime() + (extimes*1000)); // extimes second
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
2
  • I'm on my phone so I can't write you out a full solution but you need to remove the call to autocheck() after the variables and replace it with a click event for whatever selector will target the notifications list toggle. Then put a call to the checkNotifications() function inside it.
    – mrben522
    Commented Jan 11, 2019 at 19:14
  • Thanks so much for your reply, I'll waiting you back :), cuz i still newbie with that, I see my ajax calling every 1 or 2 seconds :(, I really appreciate your help. Commented Jan 11, 2019 at 19:22

1 Answer 1

0

replace the call to autocheck() with the following.

$('#ID-of-button').on('click', checkNotifications());

Of course you must replace ID-of-button with the ID of the toggle button for the notification bar. This will run the ajax call when the button is clicked, open or close.

3
  • Thank you @mrben522, I removed all autocheck call and replaced as you said but not working! I still seeing the ajax calling every 2 second, and i don't know which part doing this :(. Commented Jan 11, 2019 at 22:33
  • Hello, Any hope to fix that! Commented Jan 12, 2019 at 14:12
  • Try removing the call to autocheck(changed) inside checkNotifications. That might do it
    – mrben522
    Commented Jan 12, 2019 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.