• 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

    • The Irony... China is what it is today because of Apple 😂
    • Microsoft makes it easier to find PC specs in Windows 11 Settings by Taras Buria Windows 11 has already received several improvements that make it easier to learn about your computer's specifications. Recently, Microsoft released Spec Cards for the System > About section, which provide basic information about the PC's main components, such as processor, memory, storage, graphics card, and video memory. Now, the Settings app is getting a new way to find your device info. Microsoft wants to display basic device information right on the Home page of the Settings app. The latest preview builds from the Dev and Beta Channels introduced a new "Your device info" card for the Settings' Home page. It displays specs like processor name and speed, graphics card and the amount of video memory, storage, and RAM. The card also has a link to the "About" section, where you will find more information about your computer, its Windows edition, product ID, and the recently introduced FAQ section that answers common hardware-related questions. The "Your device info" card joins the existing cards on the Settings app's home page. While the section offers useful information like quick access to Bluetooth devices, Wi-Fi, personalization, and recommended settings, users received it with mixed reactions, as many considered it another way for Microsoft to promote its services and subscriptions like Microsoft 365, OneDrive, and Game Pass (seriously, who thinks about Game Pass when opening Settings?). Now, the Settings' Home page is a bit more useful, as it saves you a few clicks when checking your computer's specs. If you want to test the new "Your device info" card, update your PC to build 26200.5622 or newer (Dev Channel). Just keep in mind that Microsoft is rolling it out gradually, and it requires signing in with a Microsoft Account in the United States. Other changes in build 26200.5622 include a new Settings section for Quick Machine Recovery, widget improvements, more app recommendations in the "Open with" dialog, and more. Check out the full release notes here.
    • Ponies will finally have good games to play after replaying Last of Us for the 100th time. Oh and I lied, Silent Hill f looks pretty great too, but we already knew about that.
    • China blocks Apple-Alibaba AI venture in retaliation for the US trade war by Hamid Ganji iPhones sold in China, Apple's second biggest market, still lack AI features. While Apple tried to solve the issue by forming an AI venture with China's e-commerce giant Alibaba, the move has faced setbacks from China's regulator, presumably to get back at the US trade war under the Trump administration. According to a new report by Financial Times, citing people familiar with the matter, Apple and Alibaba have been working on their AI venture over the past few months, hoping to bring some AI features to iPhones sold in China. However, the Cyberspace Administration of China hasn't approved the collaboration. Every new iPhone sold worldwide has built-in ChatGPT as a result of the Apple and OpenAI partnership. Since OpenAI has no official presence in China, Apple must partner with local tech companies like Alibaba to offer AI capabilities on iPhones sold in the country. The move could help Apple navigate China's regulatory restrictions, but it's now stalled due to the US-China trade war. The Cyberspace Administration of China doesn't publicly confirm whether halting the Apple-Alibaba AI venture is a response to the US trade war. Still, sources claim this is China's response to the recent tariff clash with the US. China also has a pretty solid record of retaliating against the US reciprocal tariffs. However, the Apple and Alibaba AI partnership also has some opponents in the US. Lawmakers and government officials in Washington have raised concerns about the AI deal. They fear that this collaboration could significantly bolster China's AI capabilities.
    • Raspberry Pi Imager 1.9.4 released bringing performance improvements, bug fixes and more by David Uzondu Raspberry Pi Imager 1.9.4 is now out, marking the first official release in its 1.9.x series. This application, for anyone new to it, is a tool from the Raspberry Pi Foundation. It first came out in March 2020. Its main job is to make getting an operating system onto a microSD card or USB drive for any Raspberry Pi computer super simple, even if you hate the command line. It handles downloading selected OS images and writing them correctly, cutting out several manual steps that used to trip people up, like finding the right image version or using complicated disk utility tools. This version brings solid user interface improvements for a smoother experience, involving internal tweaks that contribute to a more polished feel. Much work went into global accessibility, adding new Korean and Georgian translations. Updates also cover Chinese, German, Spanish, Italian, and many others. Naturally, a good number of bugs got squashed, including a fix for tricky long filename issues on Windows and an issue with the Escape key in the options popup. Changes specific to operating systems are also clear. Windows users get an installer using Inno Setup. Its program files, installer, and uninstaller are now signed for better Windows security. For macOS, .app file naming in .dmg packages is fixed, and building the software is more reliable. Linux users can now hide system drives from the destination list, a great way to prevent accidentally wiping your main computer drives. The Linux AppImage also disables Wayland support by default. The full list of changes is outlined below: Fixed minor errors in Simplified Chinese translation Updated translations for German, Catalan, Spanish, Slovak, Portuguese, Hebrew, Traditional Chinese, Italian, Korean, and Georgian Explicitly added --tree to lsblk to hide partitions from the top-level output CMake now displays the version as v1.9.1 Added support for quiet uninstallation on Windows Applied regex to match SSH public keys during OS customization Updated dependencies: libarchive (3.7.4 → 3.7.7 → 3.8.0) zlib (removed preconfigured header → updated to 1.4.1.1) cURL (8.8 → 8.11.0 → 8.13.0) nghttp2 (updated to 1.65.0) zstd (updated to 1.5.7) xz/liblzma (updated to 5.8.1) Windows-specific updates: Switched to Inno Setup for the installer Added code signing for binaries, installer, and uninstaller Enabled administrator privileges and NSIS removal support Fixed a bug causing incorrect saving of long filenames macOS-specific updates: Fixed .app naming in .dmg packages Improved build reliability and copyright Linux-specific updates: System drives are now hidden in destination popup Wayland support disabled in AppImage General UI/UX improvements: Fixed OptionsPopup not handling the Esc key Improved QML code structure, accessibility, and linting Made options popup modal Split main UI into component files Added a Style singleton and ImCloseButton component Internationalization (i18n): Made "Recommended" OS string translatable Made "gigabytes" translatable Packaging improvements: Custom AppImage build script with Qt detection Custom Qt build script with unprivileged mode Qt 6.9.0 included Dependencies migrated to FetchContent system Build system: CMake version bumped to 3.22 Various improvements and hardening applied Removed "Show password" checkbox in OS customization settings Reverted unneeded changes in long filename size calculation Internal refactoring and performance improvements in download and extract operations Added support for more archive formats via libarchive Lastly, it's worth noting that the system requirements have changed since version 1.9.0: macOS users will need version 11 or later; Windows users, Windows 10 or newer; Ubuntu users, version 22.04 or newer; and Debian users, Bookworm or later.
  • Recent Achievements

    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • Rookie
      GTRoberts went up a rank
      Rookie
    • First Post
      James courage Tabla earned a badge
      First Post
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      397
    2. 2
      +FloatingFatMan
      177
    3. 3
      snowy owl
      170
    4. 4
      ATLien_0
      167
    5. 5
      Xenon
      134
  • Tell a friend

    Love Neowin? Tell a friend!