$('body').css( "margin", "20px" );
$('body').css( "padding", "20px" );
var apikey = "";
document.write ( `
<div id=maindiv>
<h1> Hello World </h1>
A 'Hello World' World which calls the API, to show how it may be called from JavaScript. <br>
<div id=enterkey style="width:60vw; background-color:white; margin:20;">
Enter API key:
<input NAME="apikey" id="apikey" VALUE='' >
<button onclick='setkey();' class=ab-normbutton >Set API key</button>
</div>
<div style="width:60vw; background-color:white; margin:20;">
<label for="textToTranslate">Input for translation:</label>
<input id=textToTranslate >
<button onclick="translateText();" class=ab-normbutton > Send </button>
</div>
<!-- Target Language -->
<div style="width:60vw; background-color:white; margin:20;">
<label for="targetLanguage">Target Language:</label>
<input id="targetLanguage">
</div>
</div>
<p id="translationOutput"></p>
`);
function setkey()
{
apikey = jQuery("input#apikey").val();
apikey = apikey.trim();
$("#enterkey").html ( "<b> API key has been set. </b>" );
}
function translateText()
{
const textToTranslate = document.getElementById('textToTranslate').value;
const targetLanguage = document.getElementById('targetLanguage').value;
const translateAPIUrl = `https://translation.googleapis.com/language/translate/v2?key=${apikey}`;
const data = {
q: textToTranslate,
target: targetLanguage,
};
console.log (data); // MH edit
fetch(translateAPIUrl, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => {
console.log (data); // MH edit
const translationResult = data.data.translations[0].translatedText;
document.getElementById("translationOutput").innerHTML = "The translation is: " + translationResult;
})
.catch(error => console.error('Error:', error));
}
/* References:
[1] https://ancientbrain.com/world.php?world=2850716357 // API Key part
*/