Tuesday, 17 September 2013

JQuery Catergory Search with Remote Results and Cashing

JQuery Catergory Search with Remote Results and Cashing

I have looked extensively through SO and I have looked at many examples,
however I can not figure out how to get my project working as a whole.
Here is the code I am using:
http://jsfiddle.net/7mY3N/
HTML5
:
<div class="ui-widget">
<label for="search">Search: </label>
<input id="search" />
<p id="empty-message"></p>
</div>
CSS3:
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center
no-repeat;
}
JQuery:
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category +
"</li>" );
currentCategory = item.category;
}
that._renderItemData( ul, item );
});
}
});
</script>
<script>
$(function() {
var cache ={};
$( "#search" ).catcomplete({
minLength: 0,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "search_basic.php", request, function( data,
status, xhr ) { // Remote results file is located at
search_basic.php
cache[ term ] = data;
response( data );
});
// If there are no results notify the user
if (ui.content.length === 0) {
$("#empty-message").text("No results found");
} else {
$("#empty-message").empty();
}
}
});
});
</script>
What I am trying to do is be able to search through results that are in
another file located at "/search_basic.php". I would like the results to
be categorized and cached in browser for future. If no results are
available, the user should also be notified. I am able to do each of these
separately except for pulling the results from a remote file and caching.
The following is the contents of search_basic.php:
header('Content-Type: application/json');
[
{ "label": "annhhx10", "category": "Products" },
{ "label": "annttop", "category": "Products" },
{ "label": "anders", "category": "People" },
{ "label": "andreas", "category": "People" }
]
If you don't mind walking me through how to get this working so that I can
learn from my mistake that would be great! Thank you!

No comments:

Post a Comment