Just finishing up an app and I need to implement one more thing on the json side of things.
I have a jquery auto complete which uses a web service I wrote which returns json.
I need to alter this a slight bit so that if the first request with paramaters returns null then it will try again with a default url without paramters which does a master search.
Just to be sure I'm not missing any tricks I said I'd ask and see if any jquery gurus have an elegant way of achieving this.
var cache = {},lastXhr;
var web_service_url_default = "http://json_sample.php";
var web_service_url_specific = "http://json_sample.php/?param1=hello¶m2=world";
var autocomp_opt = {
minLength: 1,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( web_service_url_specific, request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
};
That is my options variable for the auto complete which is input to the auto-complete call as follows and which works fine.
$('.some_class').autocomplete(autocomp_opt);
I need to alter it so that if the first request returns empty then it fires the default request with no params.
Cheers for the help as always.
Updated with working example
Got this done, see the following code in case it helps anyone. It may not be the most elegant but it works anyway.
Note that in this example and in testing the caching did not seem to play nice and caused the request not to be fired now and again so I removed it. Now it works 100%.
var autocomp_opt = {
minLength: 1,
source: function( request, response ) {
var term = request.term;
lastXhr = $.getJSON( web_service_url_specific, request, function( data, status, xhr ) {
// check if there is only one entry in the json response and if the value is null, my json script returns empty like this
if(data.length == 1 && data[0].value == null){
$.getJSON( $web_service_url_default, request, function( data, status, xhr ) {
response( data );
});
}else{
response( data );
}
});
}
};
$('.some_class').autocomplete(autocomp_opt);
if(data.length == 1 && data[0].value == null)
{
...
}
I managed to get this one working myself. See the example above if it helps anyone. It might not be the most elegant way to do this but it works nonetheless. Cheers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With