Question

I am trying to convert from the current version of MS Bing Translator to the new Azure one.

I created an access token as described in the new documentation and although the following example (for Azure) supplied by Microsoft works correctly:

function translate() {

  var from = "en", to = "es", text = "hello world";
  var s = document.createElement("script");
  s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
            "?appId=" + settings.appID +
            "&from=" + encodeURIComponent(from) +
            "&to=" + encodeURIComponent(to) +
            "&text=" + encodeURIComponent(text) +
            "&oncomplete=mycallback";
  document.body.appendChild(s);
}

function mycallback(response) {
  alert(response); 
}

I would like to convert the above code to a jQuery call.

I modified a similar jQuery ajax call from the previous version which worked, but a parseerror-jQuery17206897480448242277_1343343577741 was not called is issued:

  function jqueryTranslate() {
    var p = {};
    p.appid = settings.appID;
    p.to = "es";
    p.from = "en";
    p.text = "Goodbye Cruel World";
    p.contentType = 'text/html';
    $.ajax({
      url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
      data: p,
      dataType: 'jsonp',
      jsonp: 'oncomplete',
      complete: function (request, status) {
      },
      success: function (result, status) {
        alert(result);
      },
      error: function (a, b, c) {
        alert(b + '-' + c);
      }
    });
  }

I would very much appreciate and understanding of what is going wrong, so TIA for your time.

Was it helpful?

Solution

The other issue is that the Bing AppID mechanism for authenticating against translator has been deprecated.

Microsoft have a blog post detailing the process for getting access to Translator in the Windows Azure Marketplace here:

http://blogs.msdn.com/b/translation/p/gettingstarted1.aspx

There's an example in ASP.NET here: http://blogs.msdn.com/b/translation/p/gettingstarted2.aspx

The recommendation is (at least) to put your code for getting your token server side in ASP.NET,PHP,Node or something similar so that you Client ID and Client Secret aren't exposed.

Once you've gotten the access token, it needs to be written into the HTTP headers of the call to the service. The ASP.NET sample shows that, and it should be relatively easy to adapt to JQuery.

OTHER TIPS

To use the Bing Translator with authentication tokens, you first need a server-side script like this PHP script, token.php. It will be called every 9 minutes from the javascript on your web page.

<?php
$ClientID="your client id";
$ClientSecret="your client secret";

$ClientSecret = urlencode ($ClientSecret);
$ClientID = urlencode($ClientID);

// Get a 10-minute access token for Microsoft Translator API.
$url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
$postParams = "grant_type=client_credentials&client_id=$ClientID&client_secret=$ClientSecret&scope=http://api.microsofttranslator.com";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);  
$rsp = curl_exec($ch); 

print $rsp;
?>

Then this html page will display a two-box interface that translates from English to French.

Note: an earlier version of this post was missing the top 5 lines and so failed to load jQuery. (Sorry about that @db1.) The working script is online here:

http://www.johndimm.com/bingtrans/

<html>

<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

  <script language="javascript">
    var g_token = '';

    function onLoad() {
      // Get an access token now.  Good for 10 minutes.
      getToken();
      // Get a new one every 9 minutes.
      setInterval(getToken, 9 * 60 * 1000);
    }

    function getToken() {
      var requestStr = "/bingtrans/token.php";

      $.ajax({
        url: requestStr,
        type: "GET",
        cache: true,
        dataType: 'json',
        success: function (data) {
          g_token = data.access_token;
        }
      });
    }

    function translate(text, from, to) {
      var p = new Object;
      p.text = text;
      p.from = from;
      p.to = to;
      p.oncomplete = 'ajaxTranslateCallback'; // <-- a major puzzle solved.  Who would have guessed you register the jsonp callback as oncomplete?
      p.appId = "Bearer " + g_token; // <-- another major puzzle.  Instead of using the header, we stuff the token into the deprecated appId.
      var requestStr = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate";

      window.ajaxTranslateCallback = function (response) {
        // Display translated text in the right textarea.
        $("#target").text(response);
      }

      $.ajax({
        url: requestStr,
        type: "GET",
        data: p,
        dataType: 'jsonp',
        cache: true
      });
    }


    function translateSourceTarget() {
      // Translate the text typed by the user into the left textarea.
      var src = $("#source").val();
      translate(src, "en", "fr");
    }
  </script>
  <style>
    #source,
    #target {
      float: left;
      width: 400px;
      height: 50px;
      padding: 10px;
      margin: 10px;
      border: 1px solid black;
    }
    #translateButton {
      float: left;
      margin: 10px;
      height: 50px;
    }
  </style>
</head>

<body onload="onLoad();">

  <textarea id="source">Text typed here will be translated.</textarea>
  <button id="translateButton" onclick="translateSourceTarget();">Translate English to French</button>
  <textarea id="target"></textarea>

</body>

</html>

Could you try adding a jsonpCallback to your call and define a new function for it. This is what seems to be missing when I compare your jQuery code with the example from Microsoft.

  function jqueryTranslate() {
    var p = {};
    p.appid = settings.appID;
    p.to = "es";
    p.from = "en";
    p.text = "Goodbye Cruel World";
    p.contentType = 'text/html';
    $.ajax({
      url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
      data: p,
      dataType: 'jsonp',
      jsonp: 'oncomplete',
      jsonpCallback: 'onCompleteCallback',   <------------------ THIS LINE
      complete: function (request, status) {
      },
      success: function (result, status) {
        alert(result);
      },
      error: function (a, b, c) {
        alert(b + '-' + c);
      }
    });
  }

  function onCompleteCallback(response) {    <------------------- THIS FUNCTION
    alert('callback!'); 
  }

Tried the script submitted by John Dimm and it did not work for me. Returns a blank box and a status 304 Not Modified. Instead I used the PHP with Microsoft translator code at the msdn blog at this link http://blogs.msdn.com/b/translation/p/phptranslator.aspx and it worked beautifully

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top