Nathan
Nathan

Reputation: 12000

AJAX reload button sometimes prepends the same message multiple times

I have an AJAX function to check for new messages and then prepend the new messages to the #message. But, my problem is that this function triggers every 20 seconds, but whenever you click the Refresh button that instantly triggers the function, it messes up. Here is my functions for the AJAX:

function ajaxMail() {
    var message_id = $('.line:first').attr('id');
    jQuery.ajax({ //new mail
        type: 'get',
        dataType: 'text',
        url: "/employee/message/check_mail.php",
        data: {
            latest_id: message_id,
            t: Math.random()
        },
        success: function(data, textStatus) {
            $('#messages_inner').prepend(data);
        }
    });
}

function updateTitles() {
    //if(titleChange !== false) {
    $.get('update.php?type=title', function(data) {
        document.title = data;
    });
    //}
    $.get('update.php?type=header', function(data) {
        $('#heading').html(data);
    });
    $.get('update.php?type=total', function(data) {
        $('#total').html('Total messages: ' + data);
    });
    setTimeout("updateTitles();ajaxMail();", 20000);
}
updateTitles();

And for the Refresh button this is what I use:

$(document).ready(function() {
    $('#refresh').click(function() {
        ajaxMail();
        updateTitles();
    });
});

Sometimes, the same exact message gets prepended to the message div because of the button or something. (but when I refresh of course there aren't 2 of the same message anymore) This is one time when the same message was prepended multiple times:

enter image description here

First, I pressed the Refresh button and it prepended the new message. But then about 5 seconds later the funciton triggered again and for some reason prepended the same message again. Also as you can see the Inbox count says 2 because really there is only 2 ("Test" and "Test12345"), but for some reason the "Test12345" got prepended 2 times.

Does anyone know why it is doing this? I can also provide the code for check_mail.php if you need to see it.

Upvotes: 1

Views: 337

Answers (1)

sacah
sacah

Reputation: 68

I'd recommend trying cache:false too, I've had browsers caching an ajax request even through I was sending a random string along. Also, consider clearing the timeout before you set it again, as each time the refresh button is pressed it starts another timeout.

Upvotes: 2

Related Questions