Ajax XMLHTTPREQUEST

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
I am trying to make a dynamic registration form that checks the database to see whether the username is taken whenever they keyup(event). I have no idea what is wrong, I have an error message set up in case their browser does not support it but it does not seem to show. Please help

Ajax request:
Code:
function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  }    
  return request;
}
PHP DB check file:
PHP:
<?php #usernames check PHP script
   try
   {
     $dbh = new PDO("mysql:host=localhost;dbname=sikuneh_stbnl", "sikuneh_sikuneh", "PASSWORD");
     $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   }
   catch (PDOException $e)
   {
     print ("Could not connect to server.\n");
     print ("getMessage(): " . $e->getMessage () . "\n");
   }
$username = $_GET['username'];

$sth = $dbh->query("SELECT username FROM users WHERE username = '$username'");
$count = 0;
while($row = $sth->fetch()) {
    $usernames = $row['username'];
    $count++;
}
if($count == 0)    
    echo "<span style=\"color:green;\">Available</span>";
else
    echo "<span style=\"color:red;\">Unavailable</span>";
?>
HTML form:
HTML:
<h2>Register!</h2>
<form action="index.php" method="post" onkeyup="validateForm()" onclick="validateForm()" enctype="multipart/form-data">
<table border="0">
<tr>
<td><b>Username:</b>
<td><input type="text" id="name" name="name" onkeyup="checkUsername()" size="12"  /> 4-12 characters</td>
<td><span class="error" id="help1"></span></td>
</tr>
<tr>
<td><b>Password:</b></td>
<td><input type="password" id="password" name="password" size="12" /> 4-12 characters</td>
<td><span class="error" id="help2"></span></td>
</tr>
<tr>
<td><b>Confirm<br />Password:</b></td>
<td><input type="password" id="cpassword" name="cpassword" size="12" /> 4-12 characters</td>
<td><span class="error" id="help3"></span></td>
</tr>
<tr>
<td><b>Email:</b></td>
<td><input type="text" id="email" name="email" size="30" /></td>
<td><span class="error" id="help4"></span></td>
</tr>
<tr>
<td><b>Confirm<br />Email:</td>
<td><input type="text" id="cemail" name="cemail" size="30" /></td>
<td><span class="error" id="help5"></span></td>
</tr>
<tr>
<td><b>Gender: </td>
<td colspan="2"><label><input type="radio" name="gender" id="radio1" value="0" />Male</label> <label><input type="radio" name="gender" value="1" id="radio2" />Female</label> * Required</td>
</tr>
<tr>
<td><b>Age:</td>
<td colspan="2"><input type="text" name="age" /> * Leave blank if you do not wish to disclose</td>
</tr>
<tr>
<td><b>Location:</td>
<td colspan="2"><input type="text" name="location" /> * Leave blank if you do not wish to disclose</td>
</tr>
<tr>
<td><b>Avatar:</td>
<td colspan="2"><input type="file" name="avatar" /> * Required</td>
</tr>
<tr>
<td><input type="submit" value="Go!" id="go" /><input type="hidden" name="p" value="registerFinish" /></td>
</tr>
<tr>
<td colspan="3"><span id="help"></span></td>
</tr>
</table>
</form>
JS Ajax connection script:
Code:
<script type="text/javascript">
function checkUsername() {
  
request = createRequest();
  if (request == null)
    document.getElementById("help1").innerHTML = "Unable to create request";
  else {
    
var theName = document.getElementById("name").value;
    
var username = escape(theName);
    
var url= "checkUsernames.php?username=" + username;
  request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
document.getElementById("help1").innerHTML = request.responseText;
}
}
}
   
 request.open("GET", url, true);
    request.send(null);
}
}
</script>
I have no idea what is wrong so I am assuming it can be anything. Ignore validateForm()
 
Last edited:

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
Step 1: put debugging code into ajax code....

Code:
<script type="text/javascript">

function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  }    
  return request;
}


function checkUsername(){


  
request = createRequest();
if (request == null){
    document.getElementById("help1").innerHTML = "Unable to create request";
    alert( "in here error: no request object" ) ;
 } else {
    
   var theName = document.getElementById("name").value;
    
   var username = escape(theName);
    
   var url= "checkUsernames.php?username=" + username;
   request.onreadystatechange = function() {
     if (request.readyState == 4) {
        alert( "answer back from " + url ) ;
        if (request.status == 200) {
           alert( "good answer: " + request.responseText ) ;
           document.getElementById("help1").innerHTML = request.responseText;
        } else {
           alert( "Error: " + request.status + " : " + request.statusText ) ;
        }
     }
  }
   
 request.open("GET", url, true);
    request.send(null);
}
}
</script>

Step 2: follow alerts to problem. wild guess is that you get a 404 error.
 
Last edited:

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
Hmm, there is a XMLHTTPREQUEST object.statusText property? Thanks, I got it.
 
Last edited:

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
I have a question about getting the usernames that have already been used. I was wondering which would be faster.

(A) Which I used:
PHP:
$username = $_GET['username'];
$sth = $dbh->query("SELECT username FROM users WHERE username = '$username'");
if($sth->columncount() === 0)
  echo "Available";
else
 echo "Unavailable";

Or
(B) Which I did not use:
PHP:
$username = $_GET['username'];
$sth = $dbh->query("SELECT username FROM users");
$takenNames = array();

while($row = $sth->fetch()) {
 $username = $row['username'];
 $takenNames[] = $username;
}

for($i=0;$i<sizeof($takenName);$i++) {
 if($username == $takenName[$i]) {
  echo "Unavailable";
  break;
 }
}

Or some other way which I did not think of which is faster than either.

Edit: Sorry for double posting but I could not edit my last post.
 
Last edited:

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
(A) is faster.
If you don't already have an index on the users table based on the username column, you can add one which will speed up searches, especially if you have a large table.

(B) rewrite for speed

PHP:
$username = $_GET['username'];
$sth = $dbh->query("SELECT username FROM users");

$message = "Available" ;

if( !$sth ){
   $message = "Unavailable" ;  # I would use another message during development
} else {
  while($row = $sth->fetch()) {
    if( $username ==  $row[0] ){
      $message = "Unavailable" ;
      break;
    }
  }
}

echo $message ;
 
Last edited:

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
I already have an index, I learned to make one whenever I made a table. Thank you for the help.
 
Top