COp COp - 4 months ago 10
jQuery Question

JQUERY when user types too quickly

I am working on search system and here is my html code

<input type="text" class="SearchChats" placeholder="Search">
<div class="resc">

</div>


and this is my jquery/AJAX code

$(".SearchChats").keyup(function(e) {
var val=$(this).val();
if (e.which >= 47 && e.which <= 90 || e.which==8){
if (val!="") {
$(".resc").empty();
$(".resc").show();
$.ajax({
url: '../files/connect.php',
type: 'GET',
cache: false,
contentType: false,
processData: false,
data:"SCTS="+val,
success: function(ret)
{
$(".resc").append(ret);
}
});
$(".overviewrap").hide();
}else{
$(".resc").hide();
$(".overviewrap").show();
}
}
});


and my connect.php

if (isset($_GET['SCTS'])) {
$Value=$_GET['SCTS'];
$Value=strtolower($_GET['SCTS']);
$querya=$con->query("SELECT * FROM followers WHERE Follower='$NameId'");
$followings=[];
$count=0;
while ($Folrow=$querya->fetch_row()) {
$query=$con->query("SELECT Username FROM users WHERE Id='$Folrow[2]'");
$Namerow=$query->fetch_row();
$NameChat=$Namerow[0];
if (strpos($NameChat, $Value) !== false) {
$ProfilePicQuery=$con->query("SELECT Profile_pic FROM user_opt WHERE Username='$Folrow[2]'");
$ProfilePicRow=$ProfilePicQuery->fetch_row();
?>
<div class="overview">
<img src='../users/<?php echo $ProfilePicRow[0] ?>' class="overviewimg" />
<span class="overviewspan"><?php echo $NameChat;?></span>
</div>
<?php
$count++;
}
}


The problem is when user types m it gives all users that start with
m
but when user types Murad really quickly it gives back user with name
Murad
but duplicates it 5 times(because it has got 5 charachters)

Answer

Firstly, you should add a timeout to decrease the number of ajax requests. Secondly, you can abort any ajax request while the user is still typing, and thirdly you should start search after a certain number of characters have been pressed.

Try the following:

var searchChatsTimeout = false;
var ajaxQuery = false;
$(".SearchChats").keyup(function(e) {

  clearTimeout(searchChatsTimeout);
  if (ajaxQuery !== false) {
    ajaxQuery.abort();
  }
  var val = $(this).val();

  if (val === '') {

      $(".resc").hide();
      $(".overviewrap").show();

      return;
  }

  searchChatsTimeout = setTimeout(function(){

            ajaxQuery = $.ajax({
                url: '../files/connect.php',
                type: 'GET',
                cache: false,
                contentType: false,
                processData: false,
                data:"SCTS="+val,
                success: function(ret)
                {
                     // Empty and Show .resc only if the query is successful
                     $(".resc").empty();
                     $(".resc").show();

                     $(".resc").append(ret);

                     // hide overviewrap if query is successful
                     $(".overviewrap").hide();
                }
            });


  }, 400);

});
Comments