Originally Published at https://rapidapi.com/blog/google-translate-api-tutorial/.
We are back with yet another tutorial on Google Translate API. This time we are going to address the language personalization feature on the web with this API.
As a non-native English speaker, if you come across a web form in English that you want to fill out and submit, it can be difficult to interpret the meaning of each form field. Using the Google Translate API, we can build language personalization features for web forms so that you can choose the language while filling out the form.
If this sounds interesting, then follow along this blog post to build a demo web form with language translation capability, powered by RapidAPI. But first, a very brief introduction to Google Translate API.
A quick glance into the API endpoints tells us that it supports two endpoints.
To begin using the Google Translate API, you’ll first need to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.
RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.
Once signed in, log in to your RapidAPI account and access the API console. Click on the “Pricing” tab and opt-in for the basic subscription that gives you 50 free API calls to Google Translate API per day.
Select the “POST Translate” endpoint within the API console.
The default values of parameters indicate that we are going to translate the text “Hello, world!” to Spanish (with language code ‘es’).
Trigger the API, and you should see the translated text in the API response (JSON format).
So, “Hello, world!” in Spanish translates to “Hola Mundo!”.
If you want to try translating to other languages then you can check out the language codes defined as per the ISO 639 code definitions.
Here is what a plain form looks like:
With some translation magic, here is how you can add some spark to it.
Follow the steps below to build a demo HTML page containing this form with a translation feature.
<!DOCTYPE html> <html> <head> <title>Web Form With Language Translation</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <style type="text/css"> body { background-color: #2ecc71; font-family: source-sans-pro, sans-serif; } h1 { margin-left: auto; margin-top: 50px; text-align: center; font-weight: 100; font-size: 2.8em; color: #ffffff; } div { width: 500px; margin: auto; } .formStyle { background-color: #2ecc71; padding: 20px; width: 400px; margin-bottom: 20px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #ecf0f1; border-top-style: none; border-right-style: none; border-left-style: none; font-size: 1em; font-weight: 100; color: #ffffff; } .formButton { float: right; background-color:#ffffff; display:inline-block; color:#2ecc71; font-size:28px; font-weight: 500; padding:6px 24px; margin-top: 15px; margin-right: 60px; text-decoration:none; } .formButton:hover { background-color: #27ae60; color:#ffffff; } .formButton:active { position:relative; top:3px; } .translate { margin-left: auto; margin-top: 50px; text-align: center; font-weight: 100; font-size: 2.8em; width:50%; } .translate-option { width:50%; } /*To remove the outline that appears on clicking the input textbox*/ input:focus { outline: none; } /* To format the placeholder text color */ ::-webkit-input-placeholder { color: #ecf0f1; } :-moz-placeholder { /* Firefox 18- */ color: #ecf0f1; } ::-moz-placeholder { /* Firefox 19+ */ color: #ecf0f1; } :-ms-input-placeholder { color: #ecf0f1; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-sm"> </div> <div class="col-sm"> <div class="btn-group dropright translate"> <button id="langSel" type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Translate to </button> <div class="dropdown-menu translate-option"> <a class="dropdown-item" href="#" tolang="en">English (default)</a> <a class="dropdown-item" href="#" tolang="it">Italian</a> <a class="dropdown-item" href="#" tolang="es">Spanish</a> <a class="dropdown-item" href="#" tolang="de">German</a> </div> </div> <h1 id="formHeading"> Contact Form </h1> <div> <form action=""> <input type="text" name="name" class="formStyle" placeholder="Name" required /> <input type="text" name="email" class="formStyle" placeholder="Contact No." required /> <input type="email" name="email" class="formStyle" placeholder="Email" required /> </form> </div> </div> <div class="col-sm"> </div> </div> </div> </body> </html>
It also imports JQuery for performing all the UI operations that we describe subsequently.
<script>
block inside the <head>
and add the “click” event handler for the dropdown menu inside a $(document).ready( )
block.
<script type="text/javascript"> $(document).ready(function(){ $(".dropdown-item").click(function(e){ }); }); </script>
We will come back to this event handler and add the logic inside it.
We define a global variable “settings” to contain the AJAX call parameters, with some modifications. And then add a new function to handle the AJAX call.
var settings = { "async": true, "crossDomain": true, "url": "https://google-translate1.p.rapidapi.com/language/translate/v2", "method": "POST", "headers": { "x-rapidapi-host": "google-translate1.p.rapidapi.com", "x-rapidapi-key": "<YOUR_RAPIDAPI_KEY>", "content-type": "application/x-www-form-urlencoded" }, "data": { "source": "en", "q": "Contact Form | Name | Contact Number | Email", "target": "" } } function fetchTranslation(){ $.ajax(settings).done(function (response) { console.log(response); var translatedText = response.data.translations[0].translatedText; updatePlaceholders(translatedText); }); }
Be sure to replace the <YOUR_RAPIDAPI_KEY> placeholder with your RapidAPI subscription key in the variable settings. This variable also holds the data for API requests. Since there are four fields in the form to be translated, we use a single string with four tokens separated by a ‘|’ character to get the translated response from API in one call itself.
The value of the ‘target’ key for selecting the language will be set as part of the “click” event handler in step 6 below.
function updatePlaceholders(updateString){ var comp = updateString.split('|') $('form > input').each(function(idx){ $(this).prop("placeholder", comp[idx+1].trim() ); }); $("#formHeading").html(comp[0]); }
By default the language is English. So the logic of the “click” event handler should decide to trigger the API only if the selected language is not English. Before triggering, it replaces the ‘target’ key under ‘settings.data’ with the language code of target language, that we embed as an HTML attribute to the dropdown menu element.
$(".dropdown-item").click(function(e){ if($(this).attr("tolang") != 'en'){ settings.data.target = $(this).attr("tolang"); fetchTranslation(); $('button').html($(this).html()); } else { updatePlaceholders(settings.data.q); $('#langSel').html("Translate to"); } });
There you are. Now your form is capable of translating the placeholder text into three languages, Italian, Spanish and German. In case you want to get hold of the entire HTML file then here it is.
<!DOCTYPE html> <html> <head> <title>Web Form With Language Translation</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <style type="text/css"> body { background-color: #2ecc71; font-family: source-sans-pro, sans-serif; } h1 { margin-left: auto; margin-top: 50px; text-align: center; font-weight: 100; font-size: 2.8em; color: #ffffff; } div { width: 500px; margin: auto; } .formStyle { background-color: #2ecc71; padding: 20px; width: 400px; margin-bottom: 20px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #ecf0f1; border-top-style: none; border-right-style: none; border-left-style: none; font-size: 1em; font-weight: 100; color: #ffffff; } .formButton { float: right; background-color:#ffffff; display:inline-block; color:#2ecc71; font-size:28px; font-weight: 500; padding:6px 24px; margin-top: 15px; margin-right: 60px; text-decoration:none; } .formButton:hover { background-color: #27ae60; color:#ffffff; } .formButton:active { position:relative; top:3px; } .translate { margin-left: auto; margin-top: 50px; text-align: center; font-weight: 100; font-size: 2.8em; width:50%; } .translate-option { width:50%; } /*To remove the outline that appears on clicking the input textbox*/ input:focus { outline: none; } /* To format the placeholder text color */ ::-webkit-input-placeholder { color: #ecf0f1; } :-moz-placeholder { /* Firefox 18- */ color: #ecf0f1; } ::-moz-placeholder { /* Firefox 19+ */ color: #ecf0f1; } :-ms-input-placeholder { color: #ecf0f1; } </style> <script type="text/javascript"> var settings = { "async": true, "crossDomain": true, "url": "https://google-translate1.p.rapidapi.com/language/translate/v2", "method": "POST", "headers": { "x-rapidapi-host": "google-translate1.p.rapidapi.com", "x-rapidapi-key": "<YOUR_RAPIDAPI_KEY>", "content-type": "application/x-www-form-urlencoded" }, "data": { "source": "en", "q": "Contact Form | Name | Contact Number | Email", "target": "" } } $(document).ready(function(){ $(".dropdown-item").click(function(e){ if($(this).attr("tolang") != 'en'){ settings.data.target = $(this).attr("tolang"); fetchTranslation(); $('button').html($(this).html()); } else { updatePlaceholders(settings.data.q); $('#langSel').html("Translate to"); } }); }); function fetchTranslation(){ $.ajax(settings).done(function (response) { console.log(response); var translatedText = response.data.translations[0].translatedText; updatePlaceholders(translatedText); }); } function updatePlaceholders(updateString){ var comp = updateString.split('|') $('form > input').each(function(idx){ $(this).prop("placeholder", comp[idx+1].trim() ); }); $("#formHeading").html(comp[0]); } </script> </head> <body> <div class="container"> <div class="row"> <div class="col-sm"> </div> <div class="col-sm"> <div class="btn-group dropright translate"> <button id="langSel" type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Translate to </button> <div class="dropdown-menu translate-option"> <a class="dropdown-item" href="#" tolang="en">English (default)</a> <a class="dropdown-item" href="#" tolang="it">Italian</a> <a class="dropdown-item" href="#" tolang="es">Spanish</a> <a class="dropdown-item" href="#" tolang="de">German</a> </div> </div> <h1 id="formHeading"> Contact Form </h1> <div> <form action=""> <input type="text" name="name" class="formStyle" placeholder="Name" required /> <input type="text" name="email" class="formStyle" placeholder="Contact No." required /> <input type="email" name="email" class="formStyle" placeholder="Email" required /> </form> </div> </div> <div class="col-sm"> </div> </div> </div> </body> </html>
Copy the code, change the placeholder text <YOUR_RAPIDAPI_KEY> with your RapidAPI subscription key, and save it as an .html file. Open it in a web browser to experience the magic of translation.
One more obvious thing to consider for this form is the repetition of API calls. As a smart coder, you would call the API once and cache the translated response, rather than calling it every time.
Take the existing code and give it a shot at optimizing the API calls. You would save a lot while developing an app that has a lot of dynamic forms to present to visitors from all across the world.