Elvis Elvis - 21 days ago 7
JSON Question

jQuery - check if json file exists, if not use another file

I'm working on a project, where depending on user language, widget loads json file with content in that language. But since there are many languages, I need to check, if json file for that language exists, if it doesn't, need to load fallback json file (english).

My current code:

var cookieLang = Cookies.get('language');
widget = "../json/widget_";
ext = ".json";
en = 'en';
lv = 'lv';
ru = 'ru';

if (cookieLang === en){
json_url = widget + en + ext;
}else if (cookieLang === lv){
json_url = widget + lv + ext;
}else if (cookieLang === ru){
json_url = widget + ru + ext;
}

$.getJSON(json_url, function(json){
...
});


With current code I get console error /json/widget_ru.json 404 (Not Found) when file doesn't exist.

What is the best way to check if json file exists and without console errors, if doesn't exist load default one?

Answer

If your app using only JS, the the below code will help you

var cookieLang = Cookies.get('language');
widget = "../json/widget_";
ext = ".json";
en = 'en';
lv = 'lv';
ru = 'ru';

json_url_default = widget + en + ext;

if (cookieLang === en){
  json_url = widget + en + ext;
}else if (cookieLang === lv){
  json_url = widget + lv + ext;
}else if (cookieLang === ru){
  json_url = widget + ru + ext;
}

$.ajax({
 url: json_url,
 type: "GET",
 statusCode: {
    404: function() {
      $.getJSON(json_url_default, function(json){
        //code here
     });
    }
 },
 success:function(json) {
    //code here
 }
});
Comments