• 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

    • Showing people how to self host their own media is harmful, according to YouTube by David Uzondu YouTube has taken down a video from tech creator Jeff Geerling that demonstrated how to use LibreELEC, a lightweight operating system for turning devices into media centers, on a Raspberry Pi 5 for 4K video playback. The video, titled "I replaced my Apple TV—with a Raspberry Pi", originally published in May 2024, was removed in June 2025 under YouTube's "Harmful or dangerous content" policy. According to the violation notice, YouTube claimed the video showed "how to get unauthorized or free access to audio or audiovisual content, software, subscription services, or games that usually require payment." Image via Jeff Geerling Geerling strongly refuted YouTube's claims. He stated clearly, "I purposefully avoid demonstrating any of the tools that are popularly used to circumvent purchasing movie, TV, and other media content." He also emphasized that his own Network Attached Storage, or NAS, contains only legally acquired content. This isn't Geerling's first run-in with YouTube over self-hosted media tools. Last October, his tutorial titled "Better than Disney+: Jellyfin on my NAS" was hit with a similar strike for showing how to set up Jellyfin, an open source media server for organizing and streaming personal media. That strike was quickly overturned after an appeal. But this time, YouTube rejected his appeal, even though the LibreELEC video had been live for over a year, had racked up over half a million views, and contained no promotion of anything illegal. This whole thing feels a lot like what happened with youtube-dl. It's a simple command-line tool for downloading videos, used by tons of people for perfectly legal reasons like saving public domain content or backing up their own uploads. But that didn't stop the RIAA from hitting it with a DMCA takedown on GitHub, calling it a piracy tool. The community pushed back hard, and eventually it was brought back, thanks in part to support from groups like the Electronic Frontier Foundation who pointed out that not everything that can be misused is automatically bad. Side note, the youtube-dl project appears to be unmaintained (the last release was in 2021), if you're looking for an alternative, consider its very popular fork, yt-dlp. After the appeal was rejected, YouTube required Geerling to complete "policy training" to avoid a more serious, permanent strike on his channel. He eventually gave in and took the training. Anyways, if you're interested, he has uploaded the removed LibreELEC video to Internet Archive for anyone to watch.
    • Thanks to Herr Musk being a total poison pill, they can't even give those pieces of scrap away.  They can't even ship them to the UK/EU because they're completely illegal over here.  
    • Intel vs AMD? Microsoft seemingly has a clear recommendation for Windows 11 Pro PC upgrade by Sayan Sen Microsoft and its partners are now quite actively and regularly promoting the upgrade to Windows 11. Asus, for example, recently published blog posts about the "mandatory Windows 11 upgrade" that is coming as the Windows 11 end of support date nears. Microsoft itself, from time to time, urges users to upgrade to its newest OS. Back in February 2024, Microsoft released an advert highlighting the best things about Windows 11 over Windows 10. Later, in June in the same year, the tech giant busted "myths and misconceptions" surrounding a Windows 11 upgrade. And towards the end of 2024, in December, Microsoft put up a blog post outlining the gaming features a user enjoys on 11 if they were to upgrade from Windows 10. While technically there is nothing wrong with a company promoting its own product, sometimes these campaigns make little sense and they fall flat. For example, in January earlier this year, Microsoft shared a blog post headlined "Free Upgrade to Windows 11 (For a Limited Time Only)" which did not make sense as it offered little information about it being a "free upgrade," and it was rightfully, later taken down. The company is back again with a new commercial about Windows 11. This time it is aimed mainly at IT professionals and enterprises as the advert talks about upgrading to Windows 11 Pro from Windows 10. This landed a few days after Microsoft released a new backup tool for organizations for such a purpose. What is interesting is that the company is promoting Intel's vPro processors and there is no mention of AMD's Ryzen PRO parts. The commercial is posted on the Windows official YouTube channel and has been titled "Right side of risk | Windows 11 Pro and Intel". The video description says, "Windows 10 support ends October 14. Stay on the right side of risk—upgrade now to the power of Windows 11 Pro PCs with Intel vPro®." AMD does have a support article about the subject headlined "Support Your Customers’ Move to Windows 11, With AMD Ryzen™ PRO Processors" and you can find it here. This is not the first time Microsoft has promoted Intel CPUs over AMD ones. Back in 2021, the company also put up a full page explaining how users should "look for the Intel EVO badge" on a new device before making a purchase decision because such PCs are "verified wonderful" which was a bit of an odd language. Like the limited upgrade time article, the page above was taken down after we reported on it (can be viewed via the archive) and replaced with something else. The new commercial was published about a couple of days ago, and it is possible that Microsoft may have a dedicated AMD advert too in the pipeline scheduled for a later release, and that would only be fair if both companies get a similar treatment.
    • Don’t blame web developers for the downfall of Firefox. 😂
  • Recent Achievements

    • 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
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      436
    2. 2
      +FloatingFatMan
      238
    3. 3
      snowy owl
      216
    4. 4
      ATLien_0
      209
    5. 5
      Xenon
      154
  • Tell a friend

    Love Neowin? Tell a friend!