php - JQUERY when user types too quickly -
i working on search system , here html code
<input type="text" class="searchchats" placeholder="search"> <div class="resc"> </div>
and 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 connect.php
if (isset($_get['scts'])) { $value=$_get['scts']; $value=strtolower($_get['scts']); $querya=$con->query("select * followers follower='$nameid'"); $followings=[]; $count=0; while ($folrow=$querya->fetch_row()) { $query=$con->query("select username users id='$folrow[2]'"); $namerow=$query->fetch_row(); $namechat=$namerow[0]; if (strpos($namechat, $value) !== false) { $profilepicquery=$con->query("select profile_pic user_opt 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 when user types m gives users start m
when user types murad gives user name murad
duplicates 5 times(because has got 5 charachters)
firstly, should add timeout decrease number of ajax requests. secondly, can abort ajax request while user still typing, , thirdly should start search after number of characters have been pressed.
try 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 , show .resc if query successful $(".resc").empty(); $(".resc").show(); $(".resc").append(ret); // hide overviewrap if query successful $(".overviewrap").hide(); } }); }, 400); });
Comments
Post a Comment