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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.