Use JSON after caching through AJAX

I’m new in coding and currently creating a website that supports English and Russian languages. I want to change between them with no page reload, so I decided to use AJAX to achieve it and store information in JSON. I have a checkbox that changing my langString between EN and RU depending on checkbox state.

var langStr = "en";          $('#langsw').click(function(){              if($(this).prop("checked") == true){                 console.log("Checkbox is checked.");                 langStr = "ru";             }             else if($(this).prop("checked") == false){                 console.log("Checkbox is unchecked.");                 langStr = "en";             }         }); 

And this is jquery code to perform AJAX part

$.ajax({           type:'GET',           dataType:'json',           url: langStr+".json",           cache:true,           success: function(data){               $('#meet').append(data.title);               $('#meet').append(data.hr);               $('#meet').append(data.subtitle);           },           error: function(data){             console.log("there is an error")           }         }); 

My JSON is

   {     "title":"<h1 style=\"color:white; font-size: 42pt\">Name</h1>",     "hr":"<hr style=\"width:60%\">",     "subtitle":"<h1 style=\"color:#dbdbdb; font-weight:100\">Interactive resume</h1>"   } 

and the second one is the same in Russian.

Now the question: I want to cache both JSONs and then use one of them depending on the state of the checkbox, but I don’t know how to do so. If you have any ideas relating to other ways of achieving this I will be very happy to read them.

P.s English is my 2 language so forgive the mistakes.

Add Comment
1 Answer(s)

You can save the information in localstorage (altough there is a limit of how much you can save there).

You can use this formula to save raw json into localstorage

localStorage.setItem('language-ru', data); 

To get what is in localstorage you would use

const ru = localstorage.getItem('language-ru') 

So you can check, if user has the right language in his localstorage and if there is nothing, you can download it with that ajax call.

You can read more about localstorage here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.