Reputation: 45
I want to toggle between both Ajax request the english.json and the french.json using the button but I'm not sure how. Can someone help me, please? The code below simple just calls each object in the JSON.
<!doctype html>
<html>
<body>
<h1> Frenching</h1>
<button id="toggle"> toggle</button>
<p> This program changes names from English to French</p>
<h3 id="name"> </h3>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script>
<script>
//Ajax request
$("document").ready(function () {
$.getJSON("French.json").done(function (french) {
console.log(french.lastName)
});
$.getJSON("english.json").done(function (english) {
console.log(english.lastName)
});
});
</script>
//seperate files
French.Json
{
"firstName": "Merci",
"lastName": " Claudè"
}
English.Json
{
"firstName": "Gracias",
"lastName": "Claude"
}
Upvotes: 1
Views: 50
Reputation: 45
I created a global object to store the objects in the JSON and then I created a toggle function that triggers the English and the French json.
//sets a global variable
var globalState = {
viewState: true,
english: null,
french: null
};
//toggles function
$("#toggle").click(function toggleGlobalState () {
globalState.viewState = !globalState.viewState; // sets the viewState object to false
console.log(globalState); // toggles true and false
if(globalState.viewState) { // if true change name to french
$("#firstname")[0].innerHTML = globalState.french.firstName
$("#lastname")[0].innerHTML = globalState.french.lastName
} else { // if false change name to english
$("#firstname")[0].innerHTML = globalState.english.firstName
$("#lastname")[0].innerHTML = globalState.english.lastName
}
});
//Ajax request
$("document").ready(function () {
$.getJSON("French.json").done(function (french) {
globalState.french = french; // sets the french name objects in the json to a global object
$("#firstname")[0].innerHTML = globalState.french.firstName
$("#lastname")[0].innerHTML = globalState.french.lastName
}).then(function(result) {
console.log(globalState.french.firstName); //checks
});
$.getJSON("english.json").done(function (english) {
globalState.english = english; // sets the english name objects in the json to a global object
});
});
Upvotes: 1
Reputation: 869
if you don't mind calling both Ajax requests, you should store the result in a variable, and toggle the result.
var eng;
var fr;
$("document").ready(function () {
$.getJSON("French.json").done(function (french) {
fr = french;
});
$.getJSON("english.json").done(function (english) {
eng = english;
});
});
if you want to trigger that ajax only when needed, you should trigger it when the button is pressed.
var lang;
$("document").ready(function () {
toggle = function (json) {
$.getJSON(json).done(function (lang) {
lang = french;
});
}
});
Upvotes: 0