How To Build Support for Language Translating In Web Forms (Google Translate API Tutorial) [JavaScript]

google translate form app

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.

Is there a Google Translate API?

Google Translate needs no introduction. We all know about this popular service from Google, and you would have used it in the past via the Google Translate app. Under RapidAPI, you can work with the Google Translate API to call this service programmatically. Check out the API console to know more about the API.

google translate api console

A quick glance into the API endpoints tells us that it supports two endpoints.

google translate api endpoints

POST Detect

The “POST Detect” endpoint returns the language code of the text string that is passed to API as input.

POST Translate

The “POST Translate” endpoint returns the translated text for a given input string that is passed to the API as input. Along with the input string, it also expects the language code of the translated language.

Is the Google Translate API Free?

On RapidAPI, the Google Translate API is free up to 50 requests/day. Any additional API requests cost $0.05 each following the first 50 calls.

Connect to the Google Translate API

How to get access to the Google Translate API? How to get an API Key?

1. Sign Up for Free RapidAPI Account

RapidAPI Free API Key

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.

2. Subscribe to Google Translate API

google translate api pricing

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.

3. Test Your API Subscription

Let’s test your Google Translate API subscription.

Select the “POST Translate” endpoint within the API console.

google translate api test

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).

google translate api json response body

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.

Connect to the Google Translate API

How to build a Web Form with Translation Features

We now show you how to integrate this API into a web-based form. Be it a form hosted on a website or a mobile app. You can quickly integrate Google Translate into your front end code to provide language translation features.

Here is what a plain form looks like:

plain contact form

With some translation magic, here is how you can add some spark to it.

google translate form app

Follow the steps below to build a demo HTML page containing this form with a translation feature.

1. Create the Static HTML

We start with the bare-bones HTML page. The UI is based on Bootstrap and we add some CSS to spice up the form elements.

<!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/[email protected]/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.

2. Add Dropdown Click Handler

The main UI trigger for this page is the selection of language from the dropdown. Define a new <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.

3. Add JQuery AJAX Call To Invoke Google Translate API

You can get a code snippet for invoking the API from the API console of Google Translate API.

google translate api code snippet

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.

5. Add The Form Placeholder Update Code

The translated text returned by Google Translate API is deciphered based on the ‘|’ character and then replaced with the h1 tag as well as the placeholder text of the form elements. This happens inside another function updatePlaceholders( ) which is called as part of AJAX response handling.

function updatePlaceholders(updateString){

  var comp = updateString.split('|')

  $('form > input').each(function(idx){

    $(this).prop("placeholder", comp[idx+1].trim() );

  });

  $("#formHeading").html(comp[0]);

}

6. Add Login for “click” Event Handler

Finally, we are ready to add some code inside the “click” event handler to complete the functionality.

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/[email protected]/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.

Connect to the Google Translate API

Translate On!

Google Translate API is quite handy for translating short text. However, in the case of longer text, it may not be very accurate. That’s why it is well suited for this kind of application that needs translation of short text consisting of a couple of words.

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.

Other Applications

Good Luck! We will see you soon with yet another interesting API demo with RapidAPI.

Related Resources

Other Translation APIs

5
/
5
(
1

vote

)

The post How To Build Support for Language Translating In Web Forms (Google Translate API Tutorial) [JavaScript] appeared first on The Last Call – RapidAPI Blog.

Source: RapidAPI

Leave a Reply

Your email address will not be published.


*