title: Ajax check if username exists
body: <p>I am having trouble to get my code working. As a user types in a username it checks the database to see if it exists and if it does sets the <code>&lt;P id="checkusername"&gt;</code> to "Username Taken." and if not sets it to "Not Taken." I can't see why my code is not working.</p>
  
  <p>1-register.html</p>
  
  <pre><code>&lt;html&gt;
    &lt;body&gt;
      &lt;CENTER&gt;
        &lt;form name="register" action="register.php" method="post"&gt;
          Username: &lt;input type="text" name="username" onkeyup="checkUsername(this.value)" /&gt;
          &lt;P id="checkusername"&gt;checker&lt;/P&gt; 
          &lt;input type="submit" value="Login" /&gt;      
        &lt;/form&gt;
      &lt;/CENTER&gt;
  
      &lt;script type="text/javascript"&gt;
        function checkUsername(){
          var xmlhttp;
          var username=document.forms["register"]["username"].value;
          if(username.length==0){
            document.getElementById("checkusername").innerHTML="Empty";
            return;
          }
          if(window.XMLHttpRequest){
            xmlhttp=new XMLHttpRequest();
          }else{
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
  
          var url = "login.php";
          var params = "header=checkusername&amp;username="+username+"&amp;password="";
          xmlhttp.open("POST", url, true);
          xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          xmlhttp.setRequestHeader("Content-length", params.length);
          xmlhttp.setRequestHeader("Connection", "close");
  
          xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
      if(xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200){
            document.getElementById("checkusername").innerHTML=xmlhttp.responseText;
      }
        }
        xmlhttp.send(params);
      }
      &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>2-register.php</p>
  
  <pre><code>&lt;?php
    $header = $_POST["header"];
    if(header=="checkusername"){
      checkusername($_POST["username"]);
    }else{
      echo "No match: " . $header;
    }
  
    function connection(){
      $con = mysql_connect(URL, username, password);
      if(!$con){
        die('Could not connect: ' . mysql_error());
      }
      return $con;
    }
    function checkusername($username){
      $con = connection();
      mysql_select_db(database, $con);
      $result = mysql_query("SELECT * FROM users WHERE username = \"" . $username . "\";");
      while($row = mysql_fetch_array($result)){
        if(($row['username'] == $username)){
          echo "Username Taken.&lt;br/&gt;";
          return;
        }
      }
      echo "Not Taken.";
    }
    mysql_close();
  ?&gt;
  </code></pre>