Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  10] [ 2]  / answers: 1 / hits: 97227  / 13 Years ago, tue, april 12, 2011, 12:00:00

My Script to call ajax



<script language=javascript>
function search_func(value)
{
$.ajax({
type: GET,
url: sample.php,
data: {'search_keyword' : value},
dataType: text,
success: function(msg){
//Receiving the result of search here
}
});
}
</script>


HTML



   <input type=text name=sample_search id=sample_search onkeyup=search_func(this.value);>


Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.



For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.



When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.



Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.



I believe I had explained up to reader knowledge.


More From » jquery

 Answers
31

You should check if the value has changed over time:



var searchRequest = null;

$(function () {
var minlength = 3;

$(#sample_search).keyup(function () {
var that = this,
value = $(this).val();

if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: GET,
url: sample.php,
data: {
'search_keyword' : value
},
dataType: text,
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});


EDIT:



The searchRequest variable was added to prevent multiple unnecessary requests to the server.


[#92782] Monday, April 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devlin

Total Points: 474
Total Questions: 113
Total Answers: 100

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
;