• 0

Google Translate v2 using jQuery and Ajax


Question


<script type="text/javascript">
jQuery(document).ready(function($){
jQuery('.description-en').keyup(function(){
var value = jQuery(this).val();
jQuery("div.original").text(value);
});
var apiKey = "ENTER-YOUR-API-KEY-HERE";
var langSource = "en";
jQuery('a.translate-de').click(function(){
var langTarget = "de"; // The language Google will translate the text in.
var description = jQuery("div.original").val(); // Fetch source of text to translate.
var apiurl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&source=" + langSource + "&target=" + langTarget + "&q=" + description + "";
alert(apiurl); // This is just to see if all data is sent through
// Now we call the data
$.ajax({
url: apiurl + encodeURIComponent(description),
dataType: 'jsonp',
success: function(data){
// console.log(data);
console.log(data.data.translations[0].translatedText);
jQuery('.description-de').text(data); // Inserts translated text.
jQuery('span.status').text('Translation Complete!'); // Updates the status of translation if successfull.
}
});
return false;
});
});
</script>
<textarea class="description-en" rows="5" cols="20"></textarea>
<div class="original">Your description is presented here.</div>
<a href="#" class="translate-de">Translate Description</a><br>
<textarea class="description-de" rows="5" cols="20">Translation is inserted here!</textarea>
<br>Status: <b><span class="status">No Translation</span></b>
[/CODE]

I'm in need of some help to get this working. I have a text-area field box to which I enter my text in English and then I have a link that when clicked it will translate it in German and enter the translation text in another text-area field below.

I am having trouble trying to get the value of the original text when sending it through and would like some feed back to tell me what is missing or wrong with the code.

Your feedback would be greatly appreciated and any one can you use this if they wish once it works.

P.S. 'div.original' will be hidden off screen once this function works so the user will not see what they are typing appearing below the text-area field.

9 answers to this question

Recommended Posts

  • 0

Updated code: 17.12.2011 - 12:00am

I added the post method as I'm sure this is needed but the value of the description is still not fetched.


<script type="text/javascript">
jQuery(document).ready(function($){
jQuery('.description-en').keyup(function(){
var value = jQuery(this).val();
jQuery("div.original").text(value);
});
var apiKey = "ENTER-YOUR-API-KEY-HERE";
var langSource = "en"; jQuery('a.translate-de').click(function(){
var langTarget = "de"; // The language Google will translate the text in.
var description = jQuery("div.original").val(); // Fetch source of text to translate.
var apiurl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&source=" + langSource + "&target=" + langTarget + "&q=" + description + "";
alert(apiurl); // This is just to see if all data is sent through
// Now we call the data
$.ajax({
type: "GET",
url: apiurl + encodeURIComponent(description),
dataType: 'jsonp',
beforeSend: function(){
jQuery('span.status').text('Translating...'); // Updates the status of translation.
},
success: function(data){
// console.log(data);
console.log(data.data.translations[0].translatedText);
jQuery('.description-de').text(data); // Inserts translated text.
jQuery('span.status').text('Translation Complete!'); // Updates the status of translation if successfull.
},
error: function(data){
jQuery('span.status').text('Translatiion Failed!'); // Updates the status of translation if failed.
}
});
return false;
});
});
</script>
[/CODE]

  • 0

Made a few improvements but the text to translate is still not parsing through when link to translate text is clicked. Any help with the code would be very much appreciated.


<script type="text/javascript">
jQuery(document).ready(function($){
var apiKey = "ENTER-YOUR-API-KEY-HERE";
var langSource = "en";
jQuery('.description-en').keyup(function(){
var value = jQuery(this).val();
var toTranslate = jQuery(".description-en").val(); // Fetch source of text to translate.
jQuery("div.original").text(value); // This is just to see that the script is working while I'm typing.
});
jQuery('a.translate-de').click(function(e){
e.preventDefault;
var langTarget = "de"; // The language Google will translate the text in.
var apiurl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&source=" + langSource + "&target=" + langTarget + "&q=";
var text = toTranslate; // This inserts the text to translate.
alert(text); // This tells me the text to translate came through.
// Now we call the data
$.ajax({
type: "GET",
url: apiurl + encodeURIComponent(text),
dataType: 'json',
beforeSend: function(){
jQuery('span.status').text('Translating...'); // Updates the status of translation.
},
success: function(data){
// console.log(data);
console.log(data.data.translations[0].translatedText);
jQuery('.description-de').text(data); // Inserts translated text.
jQuery('span.status').text('Translation Complete!'); // Updates the status of translation if successfull.
},
error: function(data){
jQuery('span.status').text('Translatiion Failed!'); // Updates the status of translation if failed.
}
});
return false;
});
});
</script>
[/CODE]

  • 0

I have the text to translate parsing through now. I just need to fetch the results and put it into the other textarea field. Any one able to help me with this would be of great help. Thank you.


<script type="text/javascript">
jQuery(document).ready(function($){
var apiKey = "ENTER-YOUR-API-KEY-HERE";
var langSource = "en";
jQuery('.description-en').keyup(function(){
var value = jQuery(this).val();
$toTranslate = jQuery(".description-en").val(); // Fetch source of text to translate.
jQuery("div.original").text(value); // This is just to see that the script is working while I'm typing.
});
jQuery('a.translate-de').click(function(e){
e.preventDefault;
var langTarget = "de"; // The language Google will translate the text in.
var apiurl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&source=" + langSource + "&target=" + langTarget + "&q=";
var text = $toTranslate; // This inserts the text to translate.
var failed = 0;
//alert(text); // This tells me the text to translate came through.
// Now we call the data
$.ajax({
type: "GET",
url: apiurl + encodeURIComponent(text),
dataType: 'json',
beforeSend: function(){
if(failed == 1){
jQuery('span.status').text('Translating Again ...'); // Updates the status of translation.
}
else{
jQuery('span.status').text('Translating...'); // Updates the status of translation.
}
},
success: function(data){
// console.log(data);
console.log(data.data.translations[0].translatedText);
jQuery('.description-de').text(data); // Inserts translated text.
jQuery('span.status').text('Translation Complete!'); // Updates the status of translation if successfull.
},
error: function(data){
failed = 1;
jQuery('.description-de').text($toTranslate); // Insert original text if failed.
jQuery('span.status').text('Translation Failed!'); // Updates the status of translation if failed.
}
});
return false;
});
});
</script>
[/CODE]

  • 0

Something I noticed: you don't have to manually URL-encode and append all GET parameters to the request URL. jQuery will take care of them when you pass them as an object in the data attribute:

var apiurl = "https://www.googleapis.com/language/translate/v2";
// ...
$.ajax({
	type: "GET",
	data: {
	   key: apiKey,
	   source: langSource,
	   target: langTarget,
	   q: text
	},
	dataType: "json",
	// ...
});

Does this line:

console.log(data.data.translations[0].translatedText);

give you the desired output? If so, you can simply change the next line to:

jQuery('.description-de').text(data.data.translations[0].translatedText);

If not, try logging the whole data object and see if the object is structured as expected. Too many times already, I have found myself struggling with a bit of code when I was just looking at the wrong object attribute. :p

Another tip: enable the Net panel in Firebug (or whatever debugging console you use) and see what AJAX interactions are going on. You can investigate both sent and received data and try to find out where it may have gone wrong.

  • 0
  On 17/12/2011 at 20:05, Calculator said:

Something I noticed: you don't have to manually URL-encode and append all GET parameters to the request URL. jQuery will take care of them when you pass them as an object in the data attribute:

var apiurl = "https://www.googleapis.com/language/translate/v2";
// ...
$.ajax({
	type: "GET",
	data: {
	   key: apiKey,
	   source: langSource,
	   target: langTarget,
	   q: text
	},
	dataType: "json",
	// ...
});

Does this line:

console.log(data.data.translations[0].translatedText);

give you the desired output? If so, you can simply change the next line to:

jQuery('.description-de').text(data.data.translations[0].translatedText);

If not, try logging the whole data object and see if the object is structured as expected. Too many times already, I have found myself struggling with a bit of code when I was just looking at the wrong object attribute. :p

Another tip: enable the Net panel in Firebug (or whatever debugging console you use) and see what AJAX interactions are going on. You can investigate both sent and received data and try to find out where it may have gone wrong.

I tried it your way and as much as it makes more sense it's still not working. I get a 200 OK report but still nothing returns and the response on firebug is empty.

Here is my latest code.


<script type="text/javascript">
jQuery(document).ready(function($){
var apiKey = "ENTER-YOUR-API-KEY-HERE";
var langSource = "en";
jQuery('.description-en').keyup(function(){
var value = jQuery(this).val();
$toTranslate = jQuery(".description-en").val(); // Fetch source of text to translate.
jQuery("div.original").text(value); // This is just to see that the script is working while I'm typing.
});
jQuery('a.translate-de').click(function(e){
e.preventDefault;
var langTarget = "de"; // The language Google will translate the text in.
var apiurl = "https://www.googleapis.com/language/translate/v2";
var text = $toTranslate; // This inserts the text to translate.
var failed = 0;
// Now we call the data
$.ajax({
type: "GET",
url: apiurl,
data: { key: apiKey, source: langSource, target: langTarget, q: text },
dataType: 'json',
beforeSend: function(){
if(failed == 1){
jQuery('span.status').text('Translating Again ...'); // Updates the status of translation.
}
else{
jQuery('span.status').text('Translating...'); // Updates the status of translation.
}
},
success: function(data){
// console.log(data);
console.log(data.data.translations[0].translatedText);
jQuery('.description-de').text(data.data.translations[0].translatedText); // Inserts translated text.
jQuery('span.status').text('Translation Complete!'); // Updates the status of translation if successfull.
},
error: function(data){
failed = 1;
jQuery('.description-de').text($toTranslate); // Insert original text if failed.
jQuery('span.status').text('Translation Failed!'); // Updates the status of translation if failed.
}
});
return false;
});
});
</script>
[/CODE]

  • 0

When testing in firebug, console log says undefined. I added console.log for error return.


<script type="text/javascript">
jQuery(document).ready(function($){
var apiKey = "ENTER-YOUR-API-KEY-HERE";
var langSource = "en";
jQuery('.description-en').keyup(function(){
var value = jQuery(this).val();
$toTranslate = jQuery(".description-en").val(); // Fetch source of text to translate.
jQuery("div.original").text(value); // This is just to see that the script is working while I'm typing.
});
jQuery('a.translate-de').click(function(e){
e.preventDefault;
var langTarget = "de"; // The language Google will translate the text in.
var apiurl = "https://www.googleapis.com/language/translate/v2";
var text = $toTranslate; // This inserts the text to translate.
var failed = 0;
// Now we call the data
$.ajax({
type: "GET",
url: apiurl,
data: { key: apiKey, source: langSource, target: langTarget, q: text },
dataType: 'json',
beforeSend: function(data){
if(failed == 1){
jQuery('span.status').text('Translating Again ...'); // Updates the status of translation.
}
else{
jQuery('span.status').text('Translating...'); // Updates the status of translation.
}
},
success: function(data){
$fromTranslate = data.data.translations[0].translatedText;
console.log($fromTranslate); // Reports result in debug.
jQuery('.description-de').text(data.data.translations[0].translatedText); // Inserts translated text.
jQuery('span.status').text('Translation Complete!'); // Updates the status of translation if successfull.
},
error: function(data){
failed = 1;
console.log(data.error.code); // Returns a 403 in debug.
jQuery('.description-de').text($toTranslate); // Insert original text if failed.
jQuery('span.status').text('Translation Failed!'); // Updates the status of translation if failed.
}
});
return false;
});
});
</script>
[/CODE]

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Harmful to them because it affects their business. *Sigh*
    • TCL 75" 4K Smart TV hits lowest price, now less than £500 by Paul Hill Are you in the UK and looking for a massive 75-inch Ultra HD 4K HDR TV at a relatively affordable price? If so, check out this TCL (75P755K) 75-inch TV now because it’s at its lowest price of just £499.00, down 15% from £589.00. The model in question is slightly older, from 2024, but it’s still an excellent home entertainment upgrade given its feature set and aggressive price point. What you get: Features for the price The feature set of this model is definitely pretty impressive. It supports 4K HDR, wide colour gamut, and multiple HDR formats including HDR10+ and Dolby Vision. It also leverages MEMC (Motion Estimation & Motion Compensation), a proprietary algorithm from TCL that helps to reduce motion display blur and keep motion trails to a minimum. While MEMC will do heavy lifting to ensure the best picture, the TV only has a 60Hz refresh rate, but an effective rate of 120Hz thanks to efforts by TCL. This TCL model features Dolby Atmos 2.0 that immerses you more in whatever you’re watching on the TV. In terms of software, this TV comes with Google TV (based on Android) which is well-known and widely supported, ensuring you can use all the apps you depend on. It also supports Google Assistant, Chromecast, and voice control. The Chromecast support allows you to easily stream from your computer or phone to the TV to share what you’re watching to the people around you. The Google Assistant support can also be good if you have smart home devices around the house that can connect to it. The audio features for this TV are also good and mean you don’t need to buy a separate sound bar immediately. User experience and potential considerations According to What Hi-Fi, which reviewed the smaller 65-inch version of this TV, TCL’s TV delivers when it comes to HDR; gaming features such as low input lag, VRR, and Game Bar; wide colour gamut, and the operating system. What it didn’t like about the TV was the limited brightness, which degraded the HDR in bright rooms; the average motion handling; the lack of bass; the lack of local dimming; and the budget-oriented build quality. Making the smart buy decision If you can overlook its limitations, this TV could be a good pick if you need a new TV in the living room on a budget. If you are a serious gamer looking for a high refresh rate, or someone in a very bright room, then you will probably want to look elsewhere. Amazon is also offering free add-on services including wall mounting and unpack. If you do decide to pick up this TCL TV and find a fault with it, you have 30-days from getting the receipt to return it. TCL 75P755K 75-inch 4K TV: £499 (Amazon UK) - MSRP £589 / 15% off This Amazon deal is U.K. specific, and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon UK deals page here. Get Prime, Prime Video, Music Unlimited, Audible or Kindle Unlimited, free for the first 30 days As an Amazon Associate we earn from qualifying purchases.
    • I came here to post something similar, you beat me to it. Why on earth would somebody buy Windows again, even this shady grey-market cheap key, when they already have it and an upgrade from 10 to 11 is free?
    • I maintain that the Cybertruck was a social experiment.  "Can we convince the massively insecure petrol guzzling, Dodge Ram loving, right wing idiots to buy a poorly built, underpowered, underspecified, electric vehicle that they know everyone will laugh at them in"
  • Recent Achievements

    • Week One Done
      theevergreentree earned a badge
      Week One Done
    • Dedicated
      Fryer Tuck earned a badge
      Dedicated
    • Week One Done
      luxoxfurniture earned a badge
      Week One Done
    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      439
    2. 2
      +FloatingFatMan
      247
    3. 3
      snowy owl
      226
    4. 4
      ATLien_0
      212
    5. 5
      Xenon
      152
  • Tell a friend

    Love Neowin? Tell a friend!