Answered by:
jQuery - Ajax & Bing Translator?

Question
-
Hi!
I've the following code that is not working... but I don't understand why it's not working!
function Translate(text, fromLang, toLang) { var webMethod = 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate'; var parameters = "{'appId':'" + _bingTranslateAppId + "','text':'" + text + "','from':'" + fromLang + "','to':'" + toLang + "'}"; $.ajax({ type: "POST", url: webMethod, data: parameters, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert(msg); }, error: function (e) { alert(e); } }); }
I know that the example provided by Microsoft is working (http://msdn.microsoft.com/en-us/library/ff512406.aspx), but I find my code more elegant and I want to understand why it's not working.
Thanks for help.
Thursday, June 2, 2011 3:12 PM
Answers
-
this worked for me!
function ajaxTranslate(textToTranslate, fromLanguage, toLanguage) { var p = {}; p.appid = 'XXXXXXXXXXXXXXXXXXX'; p.to = toLanguage; p.from = fromLanguage; p.text = textToTranslate; $.ajax({ url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate', data: p, dataType: 'jsonp', jsonp: 'oncomplete', jsonpCallback: 'ajaxTranslateCallback', complete: function(request, status) { alert('complete: '+status); }, success: function(data, status) { alert('success: data-'+data+',status-'+status); }, error: function(request, status, error) { alert('error: status-'+status+',desc-'+error); } }); } function ajaxTranslateCallback(response) { alert('ajaxTranslateCallback('+response+')'); }
the key was changing to this exactly... jsonp: 'oncomplete',and moving the callback out of the normal ajax call.
Wednesday, July 20, 2011 1:49 AM
All replies
-
Nobody's here?
- Proposed as answer by Hülya UMMAN Özen Sunday, January 27, 2013 7:07 AM
Friday, June 3, 2011 3:11 PM -
Hello.
Try changing the type to 'GET'.
I ran into something similar trying to do a 'POST' to the AJAX services from Java. I believe that the AJAX services do not support HTTP 'POST'. I am no expert though, so I have no definitive proof of that.
-jonathan
- Marked as answer by Vikram Dendi Thursday, June 16, 2011 4:49 AM
- Unmarked as answer by bPlatypus Saturday, June 25, 2011 9:03 AM
Saturday, June 4, 2011 2:25 PM -
bPlatypus, Jonathan is right - you need to use 'GET' because you cannot use 'POST' which is not allowed due to Cross-Site-Scripting security concerns.
Jonathan - thank you!
Vikram Dendi, Group Product Manager
Microsoft TranslatorThursday, June 16, 2011 4:49 AM -
Hey!
Thanks for your answers. I tried with 'GET', but it still not working :-(
Fiddler give me this message: 'ReadResponse() failed: The server did not return a response for this request.'
I also tried to put the parameters directly into the url like this:
function Speak(jplayerId, text, language, format) { var webMethod = _bingApiUrl + "Speak?appId=" + _bingTranslateAppId + "&text=" + text + "&language=" + language + "&format=" + format; //var parameters = "{'appId':'" + _bingTranslateAppId + "','text':'" + text + "','language':'" + language + "','format':'" + format + "'}"; $.ajax({ type: "GET", url: webMethod, //data: parameters, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert(msg); }, error: function (e) { alert(e); } }); }
Do you have any idea of what is happening??Thanks
Saturday, June 25, 2011 9:07 AM -
Are you using a valid Bing Developer appId?
Vikram Dendi, Group Product Manager
Microsoft TranslatorTuesday, June 28, 2011 6:48 AM -
Hello Vikram,
Yes, I'm using a valid Bing Developer appId --> it's working with the "standard" method (as shown on msdn - in my 1st post).
By the way, with the standard method, when I click on my input button (that calls the bing translate api method), the html of this one is disappearing in firefox and chrome...... (in IE, it's ok!).
But really I find that the standard method is awful.... is it not possible to write it with ajax/jquery??? If not I'll use the google translate api...that's it!
Friday, July 1, 2011 4:30 PM -
up! Please help!!!Sunday, July 10, 2011 9:44 AM
-
up ....Friday, July 15, 2011 6:00 PM
-
Hello Vikram,
Yes, I'm using a valid Bing Developer appId --> it's working with the "standard" method (as shown on msdn - in my 1st post).
By the way, with the standard method, when I click on my input button (that calls the bing translate api method), the html of this one is disappearing in firefox and chrome...... (in IE, it's ok!).
But really I find that the standard method is awful.... is it not possible to write it with ajax/jquery??? If not I'll use the google translate api...that's it!
google translate api is deprecated and will be shut off december 1, 2011. you better figure out microsoft's translate api.read the important note at the top of the page here http://code.google.com/apis/language/translate/overview.html
Monday, July 18, 2011 3:24 PM -
hi glw ;-),
I noticed that.... and that's also why I came back here to find a solution to my problem....
But apparently nobody knows how to do ajax call with bing translate :-((( (a shame!)
Anyway, thanks for your answer ;-)
Tuesday, July 19, 2011 12:23 PM -
Ok, here is a complete, standalone html file:
First Method "Translate" is working, not the others "TranslateAjax1" and "TranslateAjax2"...
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> var _bingApiUrl = 'http://api.microsofttranslator.com/V2/Ajax.svc/'; var _bingTranslateAppId = 'YOUR-APP-ID'; var _fromLang = 'en'; var _toLang = 'fr'; var text = 'hello'; function TranslateCallback(response) { if (response != '') { $('#translationResult').html(response.toLowerCase()); } else { $('#translationResult').html('no response...'); } } function Translate() { var s = document.createElement("script"); s.src = _bingApiUrl + 'Translate?oncomplete=TranslateCallback&appId=' + _bingTranslateAppId + '&text=' + text + '&from=' + _fromLang + '&to=' + _toLang; document.getElementsByTagName("head")[0].appendChild(s); } function TranslateAjax1() { $.ajax({ type: 'GET', url: _bingApiUrl + 'Translate?oncomplete=TranslateCallback&appId=' + _bingTranslateAppId + '&text=' + text + '&from=' + _fromLang + '&to=' + _toLang, data: null, contentType: 'text/html', dataType: 'text/html', success: function (response) { $('#translationResult').html(response.toLowerCase()); }, error: function (e) { alert(e.statusText + ' - ' + e.status + ' - ' + e.responseText); } }); } function TranslateAjax2() { $.ajax({ type: 'GET', url: _bingApiUrl + 'Translate', data: 'appId=' + _bingTranslateAppId + '&text=' + text + '&from=' + _fromLang + '&to=' + _toLang, contentType: 'text/html', dataType: 'text/html', success: function (response) { $('#translationResult').html(response.toLowerCase()); }, error: function (e) { alert(e.statusText + ' - ' + e.status + ' - ' + e.responseText); } }); } </script> </head> <body onload="Translate();"> <div id="translationResult"></div> </body> </html>
Tuesday, July 19, 2011 1:30 PM -
OK, I think I found what's going wrong.... I need to make a call with 'JSONP' dataType like this:
function TranslateAjax2() { $.ajax({ type: 'GET', url: _bingApiUrl + 'Translate', data: 'appId=' + _bingTranslateAppId + '&text=' + text + '&from=' + _fromLang + '&to=' + _toLang + '&_=' + new Date().getTime(), dataType: 'jsonp', jsonp: false, processData: false, crossDomain: true, jsonpCallback: function(data, textStatus, jqXHR) { $('#translationResult').html(data); }, success: function (data, textStatus, jqXHR) { $('#translationResult').html(data); }, error: function (e) { $('#translationResult').html(e.statusText + ' - ' + e.status + ' - ' + e.responseText); } }); }
I tried many different options (type, crossDomain, processData,...) but I always return in the ERROR callback with "parseerror - 200 - ".BUT when I track the request in Fiddler, I can see the correct translation in "raw" view!!!
Any idea about that??
Thanks
Tuesday, July 19, 2011 4:03 PM -
this worked for me!
function ajaxTranslate(textToTranslate, fromLanguage, toLanguage) { var p = {}; p.appid = 'XXXXXXXXXXXXXXXXXXX'; p.to = toLanguage; p.from = fromLanguage; p.text = textToTranslate; $.ajax({ url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate', data: p, dataType: 'jsonp', jsonp: 'oncomplete', jsonpCallback: 'ajaxTranslateCallback', complete: function(request, status) { alert('complete: '+status); }, success: function(data, status) { alert('success: data-'+data+',status-'+status); }, error: function(request, status, error) { alert('error: status-'+status+',desc-'+error); } }); } function ajaxTranslateCallback(response) { alert('ajaxTranslateCallback('+response+')'); }
the key was changing to this exactly... jsonp: 'oncomplete',and moving the callback out of the normal ajax call.
Wednesday, July 20, 2011 1:49 AM -
Finally I've the solution :)
Thanks ;-)
- Proposed as answer by thefactoyweb Friday, December 23, 2011 11:01 PM
- Unproposed as answer by thefactoyweb Friday, December 23, 2011 11:02 PM
- Proposed as answer by thefactoyweb Friday, December 23, 2011 11:02 PM
- Unproposed as answer by thefactoyweb Friday, December 23, 2011 11:02 PM
Wednesday, July 20, 2011 7:38 AM -
How i can implemented this for translate the body of website , Thank´s Regards
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script src="jquery.translate.js"></script> And into the body tag ----- <script> $("body").translate("en", "es", {limit:Infinity}); </script>
Actually no works for meFriday, December 23, 2011 11:04 PM -
Translator gidişat sırça devamlılık üstü mü bu ben burada
Hulyaozen42
Sunday, January 27, 2013 7:09 AM -
The old appId method was deprecated in 2012.
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.
<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"; $.ajax({ url: requestStr, type: "GET", data: p, dataType: 'jsonp', cache: true }); } function ajaxTranslateCallback(response) { // Display translated text in the right textarea. $("#target").text(response); } 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>
- Edited by John Dimm Saturday, April 13, 2013 5:48 AM
Saturday, April 13, 2013 5:37 AM -
There is a remaining problem. The only way I could get it to work was by passing the name of the callback function, as a string, in p.oncomplete:
p.oncomplete = 'ajaxTranslateCallback';
If I use a function reference, or an anonymous function, the function is called but the response param is undefined.
p.oncomplete = ajaxTranslateCallback;
Similar problems happen with all the other variations I tried.
Seems to be something special about the Microsoft implementation. Other jsonp sites don't show this behavior.
The problem is that I can't pass data into the callback. Very annoying. Has anyone solved this?
- Edited by John Dimm Sunday, September 15, 2013 4:35 AM
Sunday, September 15, 2013 4:32 AM