Jump to content

Help with form validation – AJAX PHP JAVASCRIPT


esack

Recommended Posts

I am trying to validate a user name but I am running in to problems. I wrote a small PHP that checks is a user exists:

<?php

require_once('Connections/myConnection.php');

 

$user = $_GET['user'];

 

$sql = sprintf("SELECT * FROM login WHERE username = '%s'", $user );

$check_user = $myConnection->SelectLimit($sql) or die($myConnection->ErrorMsg() . "<br />" .$sql ."<br />");

 

if($check_user->RecordCount() == 0)

  echo "1";

else

  echo "0";

?>

 

Then I have the java script:

function checkUser(user)

{

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)

{

alert ("Browser does not support HTTP Request")

return

}

var url="check_user.php?user=" + user;

 

xmlHttp.onreadystatechange=stateChanged

xmlHttp.open("GET",url,true)

xmlHttp.send(null)

}

 

function stateChanged()

{

if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")

{

var res = xmlHttp.responseText;

else if(res == 1)

{

userCheckR = true;

document.signup_form.checkUserVal.value = "true";

}

else

{

userCheckR = false;

document.signup_form.checkUserVal.value = "false";

}

}

}

 

function GetXmlHttpObject()

{

var xmlHttp=null;

try

{

// Firefox, Opera 8.0+, Safari

xmlHttp=new XMLHttpRequest();

}

catch (e)

{

//Internet Explorer

try

  {

  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

  }

catch (e)

{

  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

}

}

return xmlHttp;

}

 

 

And in the form validation I do the following:

 

 

onClick="

var valForm = false;

checkUser(document.signup_form.username.value);

                   

if(document.signup_form.checkUserVal.value == 'true'){

    valForm = true;

}

else {

    alert('The user name is already used by another account. Please try a different user name.');

    valForm = false;

}...

 

 

I think that the problem is that the respond from ajax is registered only after the I check the values. Is there a better way? Anything would be great.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.