Google on-line translation

In this example we use the Google AJAX Language API together with Yeast-AJAX in order to develop a simple on-line translation service.

Type some text here (the translation will appear in the green box below):




The model used in the example

The only model data used in this example is the translation variable, which will hold the translated text.

<script yst="model">
  translation = "";

The Yeast code

The Yeast part of this example is so simple as the following code:

<textarea id="src" rows="4" onkeyup="translate(this)"></textarea>
<p class="content">Translation: </p>
<div id="target" yst="live"> <div class="result_sample" yst="value">$translation$&nbsp;</div> </div>

In it you can see a <textarea> element that will hold the text to be translated (labeled src). The dynamic part is coded in the <div> labeled with the target id. This <div> encloses another <div> that shows the value of the translation model variable. The target div is marked with the yst-live processing instruction (yst="ajax"). This means that it content can be re-rendered using the YST.AJAX.update function.

The target div re-rendering is performed each time the content of the src textarea is updated. When this happens, the translate function is executed.

<script type="text/javascript" src=""></script>

<script type="text/javascript">
  // Loads the Google Translation API
  google.load("language", "1");

  var abortable;
  function translate() {
    var txt = document.getElementById("src");
    var from = document.getElementById("from").value;
    var to = document.getElementById("to").value;

    abortable = setTimeout(function(){
      google.language.translate(txt.value, from, to, function(result) {
        if (!result.error) {
          translation = result.translation;
    }, 500);

The translate function gets the text to be translated and the source and target languages and sets a timeout function that invokes the Google Translation API. Once the translation is retrieved, the translated text is stored in the translation model variable and the target div is re-rendered calling YST.AJAX.update('target').

For more details about the Google Translation API in read its Developers Guide.