Reputation: 880
How do I use Microsoft Azure Translator using like Google Translator dropdown for html page?
I have an API Key of Microsoft Azure Translator.
Here is the sample screen shot:
Upvotes: 0
Views: 265
Reputation: 10370
How do I use Microsoft Azure Translator like Google Translator dropdown for HTML pages?
You can use the HTML code below to translate the text from one language to another using Microsoft Translator.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Microsoft Text Translator</title>
<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Microsoft Text Translator</h1>
<p>Translate text from one language to another:</p>
<label for="fromLang">From Language:</label>
<select id="fromLang">
<option value="en">English</option>
<option value="es">Spanish</option>
<option value="fr">French</option>
<!-- Add more language options as needed -->
</select>
<br>
<label for="toLang">To Language:</label>
<select id="toLang">
<option value="es">Spanish</option>
<option value="en">English</option>
<option value="fr">French</option>
<!-- Add more language options as needed -->
</select>
<br>
<label for="text">Text to Translate:</label>
<textarea id="text" rows="1" cols="30" placeholder="Enter text to translate"></textarea>
<br>
<button id="translateBtn">Translate</button>
<br>
<label for="output">Translation:</label>
<textarea id="output" rows="1" cols="30" readonly></textarea>
<script>
$(document).ready(function () {
$("#translateBtn").click(function () {
var fromLang = $("#fromLang").val();
var toLang = $("#toLang").val();
var text = $("#text").val();
var apiKey = "xxxxx";
var url = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=" + fromLang + "&to=" + toLang;
var location = "xxxxx";
$.ajax({
url: url,
type: "POST",
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", apiKey);
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Region", location);
},
data: JSON.stringify([{ Text: text }]),
success: function (data) {
$("#output").val(data[0].translations[0].text);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
});
});
</script>
</body>
</html>
In the above you need API Key and location
of Microsoft Azure Translator.
Output:
Reference:
Translator - Translate - REST API (Azure Cognitive Services) | Microsoft Learn
Upvotes: 1