cross-domain POST requests to Google Translate v2

If you're using the new Google Translate v2 API, there are two ways that you can translate directly from javascript, without having to use a server intermediary. The one drawback to this approach is that your API key will be visible to everyone, but this is a great approach to use for internal tools at your company or for proof-of-concept projects.

If you're only ever translating content less than 1900 characters in length, you can use a simple GET request:

var translateURL = "https://www.googleapis.com/language/translate/v2" +  
                "?key=" + TRANSLATE_API_KEY +  
                "&source=" + SOURCE_LANGUAGE +
                "&target=" + TARGET_LANGUAGE +
                "&q=" + TEXT_TO_TRANSLATE +  
                "&callback=?"; 
$.getJSON(translateURL, function(result){ 
  if(!result.error){
    // translated text in 
    // result.data.translations[0].translatedText
  }
);

Of note, we add the &callback=? to the URL, which is used by jQuery to trigger the callback once you receive your data, even though it's from another domain.

However, URLs in GET requests cannot be longer than 2000 characters (so you should check whether translateURL above is longer than that).. If you are hoping to translate more, you should use POST requests as mentioned in the REST documentation.

Here's a snippet on how to get this working using jQuery. Note the header override, as well as the "jsonp" datatype, which allows us to make a request to another domain:

$.ajax({  type:"POST",
          headers: {"X-HTTP-Method-Override":"GET"},
          url: "https://www.googleapis.com/language/translate/v2",
          dataType: "jsonp",
          data: { key: TRANSLATE_API_KEY,
                  source: SOURCE_LANGUAGE,
                  target: TARGET_LANGUAGE,
                  q: TEXT_TO_TRANSLATE },
          success: function(result){
            if(!result.error){
              // translated text in 
              // result.data.translations[0].translatedText
            }
          }
        });

With this method, you can translate up to 5,000 characters in a single request. If you want to translate more, you'll have to split up your task into multiple requests.