Elvis
Elvis

Reputation: 39

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?

Upvotes: 0

Views: 1794

Answers (2)

Syam Mohan M P
Syam Mohan M P

Reputation: 1067

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
 }
});

Upvotes: 2

Syam Mohan M P
Syam Mohan M P

Reputation: 1067

Implement file checking code on server side. check the below code ( if your app in PHP ).

Client side

var cookieLang = Cookies.get('language');

$.get('/json.php', {lang: cookieLang}, function(json){
    //code here
}.'json');

File : json.php

<?php

   $cookieLang = $_GET['lang'];

   $widget = "../json/widget_";
   $ext = ".json";

   $json_url_default = $widget . 'en' . $ext;

   $json_url = $widget . $cookieLang . $ext;

   if(file_exists($json_url))
     echo file_get_contents($json_url);
   else
     echo file_get_contents($json_url_default);

   exit;
?>

Upvotes: 0

Related Questions