Check for null response using getJson method

Just finishing the application, and I need to implement one more thing on the json side.

I have a jquery autocomplete that uses a web service that I wrote that returns json.

I need to change this bit a bit so that if the first request with parameters returns null, it will try again with the default URL without parameters, which performs the main search.

Just to be sure that I'm not missing any tricks, I said I would ask and see if any jquery guru has an elegant way to achieve this.

var cache = {},lastXhr; var web_service_url_default = "http://json_sample.php"; var web_service_url_specific = "http://json_sample.php/?param1=hello&param2=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 ); } }); } }; 

This is a parameter variable for autocomplete, which is entered automatically for complete completion, and which works fine.

 $('.some_class').autocomplete(autocomp_opt); 

I need to change it so that if the first request returns empty, it starts the default request with no parameters.

Help is welcomed, as always.


Updated with a working example.

After receiving this, see the following code if it helps anyone. It may not be the most elegant, but it still works.

Please note that in this example and during testing, caching seemed inactive and made the request immediately dismissed, so I deleted 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); 
+6
source share
2 answers
 if(data.length == 1 && data[0].value == null) { ... } 

I managed to get this work to work. See the example above if this helps anyone. It may not be the most elegant way to do this, but it works nonetheless. Greetings.

+2
source

I assume that an "empty request request" means a request is denied (for example, an error, not an empty string or so). You can build your ajax call with $ .ajax and connect to the error function:

 $.ajax({ url: web_service_url_specific, data: request, dataType, 'json', success: function( data, status, xhr ) { // not going to question this part cache[ term ] = data; if ( xhr === lastXhr ) { response( data ); } }, error: function() { // fallback ajax call $.ajax({}); } }); 
0
source

All Articles