Google Translate API Ajax via JavaScript

You can perform specific word/sentence lookups against Google Translate via the AJAX the function below.
JavaScript

You will need to go to the following address to create your own API Key before you can use it, but it's pretty straightforward.

Just call the function below with the id values for the source field and the target field.

var XMLHttpRequestObject = false; 

//check browser
if (window.XMLHttpRequest) {
	XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
	XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function translate(sourceID, targetID) {
	var apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
	var sourceFld = document.getElementById(sourceID);
	var targetFld = document.getElementById(targetID);
	var sourceText = sourceFld.value;
	var tmpURL = "https://www.googleapis.com/language/translate/v2?q=" + sourceText + "&target=es&source=en&key=" + apikey + "";
	if (sourceText!="") {
		if(XMLHttpRequestObject) {
			XMLHttpRequestObject.open("GET", tmpURL ); 
         		XMLHttpRequestObject.onreadystatechange = function() { 
         			if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { 		
         				//parse into JSON
					var json = JSON.parse(XMLHttpRequestObject.responseText);
					//raw return value
					var translatedText = json.data.translations[0].translatedText;					
					//cleanup	
					translatedText =translatedText.replace(/"/g, '"');				//replaces ALL " with "	
					//output
					targetFld.value = translatedText;
				} 
			} 
     		XMLHttpRequestObject.send(null); 
		}
	}
}

Posted by fbrefere001 on Friday May 8, 2015