I have a problem and it's the following, I have a textbox to search contacts after execute keyup event, the contacts are appended to a div, because I use pagination with the scroll too, after keyup event the content of that div is cleaned to replace it with the new content, but this happens if I write slowly, because when I write very fast, the content is not replaced but is appended to the existing content and so that is repeating the same register, may be because ajax is asynchronous and after every keyup it remains executing the request.
code
var paginam = 1;
$('div.dvusuarios').scroll(function() {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
paginam++;
listcontactosmsj($('#txtbuscaamgcon').val(), paginam);
}
});
function listcontactosmsj(contacto, paginam) {
$.ajax({
type: 'GET',
url: "<? echo PUBLIC_PATH . 'message/selcontacts' ?>",
data: 'contacto=' + contacto
+ '&pagina=' + paginam
}).done(function(data) {
$('div.dvusuarios').append(data);
});
}
listcontactosmsj('', 1);
$('#txtbuscaamgcon').keyup(function() {
paginam = 1;
$('div.dvusuarios').html('');
listcontactosmsj($(this).val(),paginam );
});
I tried to solve it like this, but this does not work
$('#txtbuscaamgcon').keyup(function() {
paginam = 1;
$('div.dvusuarios').html('');
var refrescar = setInterval(listcontactosmsj($(this).val(),paginam), 5000);
$.ajaxSetup({cache: false});
});
I don´t know what's wrong with my source code, the queries in mysql and php scripts are ok.
At the beginning, you should create a new global variable under paginam
, like so:
var paginam = 1,
contactRequest = false;
Then, change your listcontactosmsj()
function to the following:
function listcontactosmsj(contacto, paginam) {
if (contactRequest) {
contactRequest.abort();
}
contactRequest = $.ajax({
type: 'GET',
url: "<? echo PUBLIC_PATH . 'message/selcontacts' ?>",
data: 'contacto=' + contacto
+ '&pagina=' + paginam
}).done(function(data) {
$('div.dvusuarios').append(data);
contactRequest = false;
});
}
You're right about what's happening. When you type quickly, the keyup
event fires rapidly, and multiple AJAX requests are being sent rapidly. With this modification, the listcontactosmsj()
function will check to see if there's currently a request being made. If there is, it cancels the request, and starts a new one.