Google Translate Working Example

Note: This code sample no longer works ever since the Google Translate API was switched to being a paid service.

As promised, here’s a sample implementation of the Google Translate API.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Google Translate</title>
<script language="javascript" src="http://www.google.com/jsapi"></script>
<script language="javascript">
 google.load ("language", "1");
 function gtrans (f) {
  document.getElementById("translation").innerHTML = "-";
  var lang = f.langpair.value.split("|");
  google.language.translate (f.translate.value, lang[0], lang[1], function (result) {
   if (!result.error) {
    var container = document.getElementById("translation").innerHTML = result.translation;
   }
  });
  return false;
 }
</script>
</head>
<body>
<form onsubmit="return false">
 <p>Enter text to translate and click "Translate"</p>
 <textarea name="translate" cols="50" rows="5"></textarea>
 <br />
 <select name="langpair">
  <option value="ar|en">Arabic to English</option>
  <option value="zh|en">Chinese to English</option>
  <option value="zh-CN|zh-TW">Chinese (Simplified to Traditional)</option>
  <option value="zh-TW|zh-CN">Chinese (Traditional to Simplified)</option>
  <option value="nl|en">Dutch to English</option>
  <option value="en|ar">English to Arabic</option>
  <option value="en|zh-CN">English to Chinese (Simplified)</option>
  <option value="en|zh-TW">English to Chinese (Traditional)</option>
  <option value="en|nl">English to Dutch</option>
  <option value="en|fr">English to French</option>
  <option value="en|de">English to German</option>
  <option value="en|el">English to Greek</option>
  <option value="en|it">English to Italian</option>
  <option value="en|ja">English to Japanese</option>
  <option value="en|ko">English to Korean</option>
  <option value="en|pt">English to Portuguese</option>
  <option value="en|ru">English to Russian</option>
  <option value="en|es">English to Spanish</option>
  <option value="fr|en">French to English</option>
  <option value="fr|de">French to German</option>
  <option value="de|en">German to English</option>
  <option value="de|fr">German to French</option>
  <option value="el|en">Greek to English</option>
  <option value="it|en">Italian to English</option>
  <option value="ja|en">Japanese to English</option>
  <option value="ko|en">Korean to English</option>
  <option value="pt|en">Portuguese to English</option>
  <option value="ru|en">Russian to English</option>
  <option value="es|en">Spanish to English</option>
 </select>
 <input type="button" value="Translate" onclick="gtrans(this.form)" />
 <p id="translation" style="border:1px solid #00f;padding:5px;width:400px">-</p>
</form>
</body>
</html>

With this API, translating a website from one language to another will be pretty straightforward and FREE. Thanks to Google for providing us with this API, now we can finally increase usability in our websites.

Javascript Based Google Translate API Released

If you need to translate your website from one language to another then I have some good news for you. Google Translate has released a JavaScript based API that’s both easy to use and implement. It can handle 13 different languages and as much as 29 language pairs.

I already checked the API documentation and it’s definitely easy to implement. Check out my sample implementation.

AJAX Username Validation

Form input validation is sometimes an annoying part in web development but it’s something that we web developers can’t avoid. In order to make sure that the data being entered by our users are valid, we simply have to validate. Another good use of validation is to provide feedback to the user on whether what they are typing is acceptable or not.

One such case is in user registration forms wherein we ask the user to enter a username. It will be nice if we can provide them immediate feedback on whether the username they are choosing is of the correct length, contains invalid characters and of course if it’s still available. For this purpose, I wrote a 156 line AJAX file that shows how to do it.

It’s divided into three sections…

  1. The PHP section – which runs on the server to check if the username is available
  2. The Javascript section – which contains are AJAX stuff and does some client-side validation as well
  3. And the HTML Form – this is where the user enters the username

I simplified the form to contain only the username field – after all, this is just an example / tutorial.

The PHP Part

// sample code for testing purposes only
 // existing usernames
 $usernames = array ("administrator", "peterpiper", "peterpan", "superman");
 if ($_GET["u"] != "") {
  if (in_array ($_GET["u"], $usernames)) {
   // if username is in our array then output the string "0"
   echo "0";
  } else {
   // if username is not in our array then output the string "1"
   echo "1";
  }
  exit;
 }

For the purpose of providing an example, I simply entered a list of “existing” usernames into an array. In the real world, you will be checking the value of $_GET["u"] against a database.

The Javascript Part

function ajax_call (url, callback_function, error_function) {
 var xmlHttp = null;
 try {
  // for standard browsers
  xmlHttp = new XMLHttpRequest ();
 } catch (e) {
  // for internet explorer
  try {
   xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");
     } catch (e) {
   xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
     }
 }
 xmlHttp.onreadystatechange = function () {
  if (xmlHttp.readyState == 4)
   try {
    if (xmlHttp.status == 200) {
     // we got the data, let"s call the callback function
     callback_function (xmlHttp.responseText);
    }
   } catch (e) {
    // oops we have an error, call the error function
    error_function (e.description);
   }
  }
  // open the url
  xmlHttp.open ("GET", url);
  // and send the data
  xmlHttp.send (null);
 }

 /*
  * this function is called for every keypress on our input field
  * it accepts one parameter – i – which is the object referencing
  * our input field
  */
 function usercheck_init (i) {
 var obj = document.getElementById("ajax_output");
 obj.innerHTML = ""; // <- clear the status field

 if (i.value.length < 1) return;

  var err = new Array ();
 // pre-ajax checks… let"s check everything that we can check before calling ajax
 // usernames can only contain letters, numbers and underscores
 if (i.value.match (/[^a-z0-9_]/)) err[err.length] = "Username can only contain letters, numbers and underscores";
 // usernames must be at least 8 characters long
  if (i.value.length < 8) err[err.length] = "Username too short";
 // if we have a pre-ajax error, then show the error
  if (err != "") {
   obj.style.color = "#ff0000";
   obj.innerHTML = err.join ("<br />");
   return;
  }

  // all pre-ajax checks passed?  good, now let"s do our ajax check
  ajax_call ("usercheck.php?u=" + i.value, usercheck_callback, usercheck_error);
 }

 /*
  * this is our callback function
  * all it does is check the data returned by the server
  * and decide on whether we show an error or not
  */
 function usercheck_callback (data) {
  var response = (data == "1");

  var obj = document.getElementById("ajax_output");
  obj.style.color = (response) ? "#008800" : "#ff0000";
  obj.innerHTML = (response == "1") ? "Username OK" : "Username already taken";
 }
 /*
  * this is our error function
  * all it does is pop an alert box showing the error
  */
 function usercheck_error (err) {
  alert ("Error: " + err);
 }

It’s pretty self-explanatory but if you’re a bit confused then read the AJAX Introduction I wrote previously so you can grasp the idea of what’s being done in the Javascript code above.

The HTML Form

<form method="post" onsubmit="return false">
 <dl>
  <dt>Username</dt>
  <dd>
   <input type="text" name="username" value="" onkeyup="usercheck_init (this)" />
   <div id="ajax_output"></div>
  </dd>
 </dl>
</form>

A few things worth mentioning about our HTML form. First, I placed onsubmit=”return false” in the form tag – you can take that out. I just don’t want the form to be submitted when someone presses the enter key on the username field. Second is the onkeyup=”usercheck_init (this)” part. That’s what hooks our input field to our ajax call every time the user types a character in our username field.

Now, we put them all together into one nice HTML/PHP file and give it a try.

<?php
/*
 * Username Validation using AJAX
 *
 * Author: Mike Lopez
 * Author URI: http://mikelopez.info , http://coderscult.com
 *
 * Description:
 *  This AJAX example consists of three parts
 *  namely: PHP, Javascript, and HTML FORM
 *  - The PHP part handles the server side checking of the username
 *  - The Javascript part contacts the server (the PHP part)
 *  - The HTML FORM displays the username input field which is
 *    hooked to Javascript via the onkeyup attribute
 */
// *** THE PHP PART ***
// sample code for testing purposes only
 // existing usernames
 $usernames = array ("administrator", "peterpiper", "peterpan", "superman");
 if ($_GET["u"] != "") {
  if (in_array ($_GET["u"], $usernames)) {
   // if username is in our array then output the string "0"
   echo "0";
  } else {
   // if username is not in our array then output the string "1"
   echo "1";
  }
  exit;
 }

/*
 * Note: In a more realistic scenario, you will be checking
 * usernames against a database instead of just a predefined
 * array as in our example
 */
// *** END OF PHP PART ***
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Check if User Exists</title>

<!– *** THE JAVASCRIPT PART *** –>
<script type="text/javascript">
<!– // Javascript –>

/*
 * ajax_call function – this does the hard work
 * accepts three parameters:
 *  url – the url of the server side script to call
 *  callback_function – the function to call when data is retrieved from the server
 *  error_function – the function to call when an error occurs
 */
function ajax_call (url, callback_function, error_function) {
 var xmlHttp = null;
 try {
  // for standard browsers
  xmlHttp = new XMLHttpRequest ();
 } catch (e) {
  // for internet explorer
  try {
   xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");
     } catch (e) {
   xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
     }
 }
 xmlHttp.onreadystatechange = function () {
  if (xmlHttp.readyState == 4)
   try {
    if (xmlHttp.status == 200) {
     // we got the data, let"s call the callback function
     callback_function (xmlHttp.responseText);
    }
   } catch (e) {
    // oops we have an error, call the error function
    error_function (e.description);
   }
  }
  // open the url
  xmlHttp.open ("GET", url);
  // and send the data
  xmlHttp.send (null);
 }

 /*
  * this function is called for every keypress on our input field
  * it accepts one parameter – i – which is the object referencing
  * our input field
  */
 function usercheck_init (i) {
 var obj = document.getElementById("ajax_output");
 obj.innerHTML = ""; // <- clear the status field

 if (i.value.length < 1) return;

  var err = new Array ();
 // pre-ajax checks… let"s check everything that we can check before calling ajax
 // usernames can only contain letters, numbers and underscores
 if (i.value.match (/[^a-z0-9_]/)) err[err.length] = "Username can only contain letters, numbers and underscores";
 // usernames must be at least 8 characters long
  if (i.value.length < 8) err[err.length] = "Username too short";

 // if we have a pre-ajax error, then show the error
  if (err != "") {
   obj.style.color = "#ff0000";
   obj.innerHTML = err.join ("<br />");
   return;
  }

  // all pre-ajax checks passed?  good, now let"s do our ajax check
  ajax_call ("usercheck.php?u=" + i.value, usercheck_callback, usercheck_error);
 }

 /*
  * this is our callback function
  * all it does is check the data returned by the server
  * and decide on whether we show an error or not
  */
 function usercheck_callback (data) {
  var response = (data == "1");

  var obj = document.getElementById("ajax_output");
  obj.style.color = (response) ? "#008800" : "#ff0000";
  obj.innerHTML = (response == "1") ? "Username OK" : "Username already taken";
 }
 /*
  * this is our error function
  * all it does is pop an alert box showing the error
  */
 function usercheck_error (err) {
  alert ("Error: " + err);
 }
</script>
<!– END OF THE JAVASCRIPT PART –>

</head>
<body>

<!– THE FORM –>
<form method="post" onsubmit="return false">
 <dl>
  <dt>Username</dt>
  <dd>
   <input type="text" name="username" value="" onkeyup="usercheck_init (this)" />
   <div id="ajax_output"></div>
  </dd>
 </dl>
</form>
<!– END OF THE FORM –>

</body>
</html>

AJAX Introduction

Ever wondered what AJAX is? AJAX stands for Asynchronous JavaScript and XML. It is not a programming language in itself but rather a combination of different web development techniques. Furthermore, AJAX technology is not new though it has only been popularized recently especially by Google (Google Maps, GMail, Google Calendar, etc.)

At the heart of AJAX is JavaScript’s XMLHttpRequest Object. It is through this object that the browser asynchronously sends a request to the server thereby eliminating the need for a page reload. Without AJAX, the typical flow would be:

  1. User enters data into a field
  2. User presses submit button
  3. Browser sends form data to server and waits for a response
  4. Server responds back with an entire page
  5. Browser shows the returned page from the server

While the above approach works and is still being used by lots of websites, it is pretty cumbersome for the server and for the browser thereby taking more time. With AJAX, the flow would be

  1. User enters data into a field
  2. User presses submit button
  3. XMLHttpRequest sends data to server asynchronously
  4. Server responds back only with the data needed and not the entire page
  5. Javascript updates the sections of the page that only needs to be updated

While there are the same number of steps, the browser and especially the server only process data that needs to be processed and eliminates the need of an entire page reload. But how is it done?

There are many AJAX libraries available that simplifies things allowing the programmer to focus on the more important things to be done. You may use those and things will work just the same but since the purpose of this article is to introduce you to AJAX, allow me to show you my simple little function that handles all my AJAX needs.

/*
 * ajax_call function – this does the hard work
 * accepts three parameters:
 *  url – the url of the server side script to call
 *  callback_function – the function to call when data is retrieved from the server
 *  error_function – the function to call when an error occurs
 */
function ajax_call (url, callback_function, error_function) {
 var xmlHttp = null;
 try {
  // for standard browsers
  xmlHttp = new XMLHttpRequest ();
 } catch (e) {
  // for internet explorer
  try {
   xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");
     } catch (e) {
   xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
     }
 }
 xmlHttp.onreadystatechange = function () {
  if (xmlHttp.readyState == 4)
   try {
    if (xmlHttp.status == 200) {
     // we got the data, let’s call the callback function
     callback_function (xmlHttp.responseText);
    }
   } catch (e) {
    // oops we have an error, call the error function
    error_function (e.description);
   }
  }
  // open the url
  xmlHttp.open ("GET", url);
  // and send the data
  xmlHttp.send (null);
 }

The function is pretty self-explanatory so I won’t explain every line here (I’m feeling lazy). Note that this function only handles GET requests and does not handle POST but it can be easily modified to handle POST as well. I’ll leave that to you. Using it is pretty simple. Here’s an example:

/*
  * first we create a callback function to process the returned data
  * in this example, we’ll just show the data in an alert box
  */
 function fxn_callback (data) {
  alert (data);
 }
 /*
  * for error handling, we specify an error handler which simply
  * shows an alert box containing a description of the error
  */
 function fxn_error (err) {
  alert ("Error: " + err);
 }

 /*
  * then we call our ajax function passing three parameters
  * the url – in this case a plain text file
  * the callback function
  * and our error function
  */
 ajax_call ("somefile.txt", fxn_callback, fxn_error);

As you can see, it’s pretty simple. Also you may notice that we’re just returning a text file instead of an XML file. Well, that’s the beauty of it. XMLHttpRequest will return exactly what the server gave it back – XML, HTML, or just plain text and it’s up to your callback function to process that data. In my case, I prefer returning data in plain text so my server side script (PHP in this case) looks something like this.

<?php
// do some work here based on the data passed to us via GET …
echo "our return value";
exit;
?>

See how I echo the return value in my PHP script? That’s important because what’s been echoed in my PHP script is the data that will be returned to our AJAX function. Also, I added “exit;” at the end of my script to make sure that no extra data will be sent back.

To sum it all up… AJAX is not new – it’s been there for a while but rather untapped by the majority of web developers. AJAX is pretty easy to understand because it’s not a new programming language. It’s just plain old Javascript. Lastly, AJAX can process both XML and plain text data, it’s really up to you to choose.

CSS Dropdown Menu

Ever wondered how to make those drop-down menus using CSS? There are many ways to do it but they are all pretty similar. Here’s how I do it.

The CSS Code

This is the part that gives the dropdown structure. Without the CSS, all you’ll get is plain HTML only output.

/*
 CSS Dropdown Stylesheet
 by Mike Lopez

http://coderscult.com

*/
ul.dropdown {
 margin: 0;
 padding: 0;
 list-style: none;
 float: left;
 width: 100%;
}
.dropdown li {
 margin: 0;
 padding: 0;
 float: left;
 position: relative;
}
.dropdown ul {
 display: none;
 float: none;
 margin: 0;
 padding: 0;
 list-style: none;
}
.dropdown li li {
 float: none;
 display: inline;
 white-space: nowrap;
}

.dropdown li:hover ul, .dropdown li.lihover ul {
 position: absolute;
 display: block;
}

.dropdown a {
 display: block;
 padding: 3px 10px;
 margin: 0 1px 1px 0;
 font-family: Arial, Helvetica, sans-serif;
 font-size: 9pt;
 background: #080;
 color: #fff;
 text-decoration: none;
}

.dropdown a:hover {
 background: #0a0;
}

The Internet Explorer Javascript Hack

Hey! Didn’t I say CSS? Why do I need Javascript? Well, if the guys in Microsoft just followed CSS standards properly then we won’t need to put this javascript. Yes, this is here because we don’t want to make those IE users feel left out.

/*
 CSS Dropdown Javascript for Internet Explorer
 by Mike Lopez based on Son-Of-Sucker-Fish IE Hack

http://coderscult.com

*/
var liHover = function () {
 var liEls = document.getElementById ("dropdown").getElementsByTagName ("LI");
 for (var i = 0; i < liEls.length; i++) {
  liEls[i].onmouseover = function () {
   this.className += " lihover";
  }
  liEls[i].onmouseout = function () {
   this.className = this.className.replace (new RegExp (" lihover\\b"), "");
  }
 }
}
if (window.attachEvent) window.attachEvent ("onload", liHover);

The HTML

Finally, here’s the stuff that puts these things together, the html page.

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>CSS Dropdown</title>
  <link rel="stylesheet" type="text/css" href="dropdown.css" />
  <script language="javascript" src="dropdown.js"></script>
 </head>
 <body>
  <ul class="dropdown" id="dropdown">
   <li><a href="#">Link 1</a>
    <ul>
     <li><a href="#">Sublink 1-1</a></li>
     <li><a href="#">Sublink 1-2</a></li>
     <li><a href="#">Sublink 1-3</a></li>
     <li><a href="#">Sublink 1-4</a></li>
    </ul>
   </li>
   <li><a href="#">Link 2</a>
    <ul>
     <li><a href="#">Sublink 2-1</a></li>
     <li><a href="#">Sublink 2-2 lipsum</a></li>
     <li><a href="#">Sublink 2-3</a></li>
     <li><a href="#">Sublink 2-4</a></li>
    </ul>
   </li>
   <li><a href="#">Link 3</a></li>
  </ul>
 </body>
</html>

There you go. Copy and paste the code into their proper filenames and check it out. Here’s a working sample:

PHP Date Validation Using strtotime()

Here’s a nifty little script I use to validate date input with PHP. This function can accept any common date entry and return true if the date is valid or false otherwise.

The Script

<?php

function isValidDate ($dateString) {
        $x = strtotime ($dateString);
        if ($x === false || $x == -1) {
                return false;
        } else {
                return true;
        }
}

/* usage */
isValidDate ("March 18, 1977");  // returns true
isValidDate ("tomorrow");  // returns true
isValidDate ("+1 Month");  // returns true
isValidDate ("Invalid Date Here"); // returns false;

?>

Since this isValidDate uses PHP’s strtotime function, it can practically accept any English textual datetime description.