title: Validating with Ajax
body: <p>I wrote some ajax code that sends values to a php file for validation but I have a problem with it. This is my ajax code:</p>
  
  <pre><code>&lt;html&gt;
  &lt;body&gt;
  &lt;style&gt;
  #displayDiv{
  background-color: #ffeeaa;
  width: 200;
  }
  &lt;/style&gt;
  &lt;script type="text/javascript"&gt;
  function ajaxFunction(str)
  {
  var httpxml;
  try
  {
  // Firefox, Opera 8.0+, Safari
  httpxml=new XMLHttpRequest();
  }
  catch (e)
  {
  // Internet Explorer
  try
  {
  httpxml=new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch (e)
  {
  try
  {
  httpxml=new ActiveXObject("Microsoft.XMLHTTP");
  }
  catch (e)
  {
  alert("Your browser does not support AJAX!");
  return false;
  }
  }
  }
  function stateChanged()
  {
  if(httpxml.readyState==4)
  {
  document.getElementById("displayDiv").innerHTML=httpxml.responseText;
  
  }
  }
  var url="username_exists.php?username=";
  httpxml.onreadystatechange=stateChanged;
  httpxml.open("GET",url,true);
  httpxml.send(null);
  }
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;input type="text"
  onkeyup="ajaxFunction(this.value);" name="username" /&gt;&lt;div id="displayDiv"&gt;&lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>and the above code send values to username_exists.php :</p>
  
  <pre><code>&lt;?php
  $username = trim($_REQUEST['username']);
  
  if (usernameExists($username)) {
    echo '&lt;span style="color:red";&gt;Username Taken&lt;/span&gt;';
  }
  else {
    echo '&lt;span style="color:green;"&gt;Username Available&lt;/span&gt;';
  }
  
  function usernameExists($input) {
    // in production use we would look up the username in
    // our database, but for this example, we'll just check
    // to see if its in an array of preset usernames.
    $name_array =  array ('k','steve', 'jon', 'george', 'admin');
  
    if (in_array($input, $name_array)) {
      return true;
    }
    else {
      return false;
    }
  }
  ?&gt;
  </code></pre>
  
  <p>My problem is that when any username is put in the textbox returns "Username Available"! What did I do wrong?</p>