<script type="text/javascript">
var associate_search =
{
this.last_query = '';
this.last_results = new Array();
this.ajax_request = null;
// takes the keywords (a string)
// and a callback (a function with
// one single param)
this.doSearch = function(keywords, callback)
{
// if the user is still typing,
// kill any previous searches
if(this.ajax_request != null)
{
this.ajax_request.abort();
}
// if the last query is the same
// as the current one, return
// the last set of results
if(this.last_query == keywords)
{
callback(this.last_results);
return null;
}
// set the last_query to the current keywords
this.last_query = keywords;
// store a local copy of "this",
// so it can be accessed
var em = this;
// create an ajax request and
// store the request in the
// ajax_request variable (to
// abort if need be
em.ajax_request = $.ajax(
{
url : 'path to script', // obviously the path to the script
type : 'POST', // the request type, GET or POST
dataType : 'json', // the return type, if set to json and the return type is json, it will parse this to an object
data : { 'Query' : keywords }, // the data to send with the POST
success : function(data)
{
// the success callback
// set the last_results with the
// new results
em.last_results = data;
// clear the ajax_request
em.ajax_request = null;
// fire the callback with the results
callback(em.last_results);
},
error : function(error)
{
// the error callback
alert('There was an error');
}
});
// return the ajax_request
return em.ajax_request;
};
};
// the instance of associate_search
var as_instance = null;
$(document).ready(function()
{
$('#search').keyup(function()
{
// if the instance hasn't
// been defined, create it
if(as_instance != null)
{
as_instance = new associate_search();
}
// perform the search, passing
// the value of the text box
// and a callback function.
as_instance.doSearch($(this).val(), function(results)
{
// once we have got some results, so something with them!
});
});
});
</script>
Bookmarks