0

I have a problem with some of my validation code. Here it is.

function isEmailValid(email) {
 if( email == "") {
 document.getElementById("emailMsg").innerHTML="<font color=red>Email cannot be empty</font>"; 
 }
 else { 
 var emailRegexStr = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
 if (!emailRegexStr.test(email)) { 
 document.getElementById("emailMsg").innerHTML="<font color=red>Invalid email</font>"; 
 }
 else {
 xmlhttp = getHTTPObject();
 xmlhttp.onreadystatechange = function() {
 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
 document.getElementById("emailMsg").innerHTML = xmlhttp.responseText; 
 if(xmlhttp.responseText == "<font color=green>Correct !</font>" ) {
 return true;
 }
 else {
 return false;
 } 
 }
 }
 xmlhttp.open("GET","includes/register_function.php?email="+email,true); 
 xmlhttp.send();
 }
 }
}

The below part of above code is not working properly.

if (xmlhttp.responseText == "<font color=green>Correct !</font>") {
 return true;
}
else {
 return false;
}

May be a stupid mistake I am newbie in PHP + AJAX.

here is the related PHP code

if (isset($_GET['email'])) { 
 $email=$_GET['email']; 
 if (!isUserExistsByEmail($email)) {
 echo "<font color=green>Correct !</font>"; 
 } else {
 echo "<font color=red>Email already exisits</font>"; 
 } 
}

here is gethttpobject function

function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
 alert("Browser does not support AJAX.");
return null;
} 

}

i need to know how to change the getHTTPObject function for synchronous scenario .

Thanks.

asked Dec 18, 2010 at 15:03
5
  • 3
    That regular expression is going to say that a lot of perfectly valid email addresses are invalid. Commented Dec 18, 2010 at 15:06
  • 3
    I'd also say that the code you have is very fragile - what happens if someone improves the server to return better formatted html? eg <font color="green">Correct !</font> or moves spacing around etc? Commented Dec 18, 2010 at 15:09
  • ajax part is check if the email already availble in database and echo the value so to complete the whole validation if (xmlhttp.responseText == "<font color=green>Correct !</font>") should be true otherwise it is already in the database. This is a validation part in a registration form. Commented Dec 18, 2010 at 15:12
  • "<font color=green>Correct !</font>" is code for "Address not in database"? Oh my. Commented Dec 18, 2010 at 15:15
  • I'm not saying it's not a valid check to do - it definitely is. I'm just saying that the way you're doing it is likely to cause you a lot of problems. Why try to exactly match the response text when you could just check it contains the word Correct... That said, I think Asaph's answer is what you're after Commented Dec 18, 2010 at 15:16

3 Answers 3

1

You're relying on string-matching an arbitrary string - This is often error prone. Most likely there' a trailing carriage return in the response

Try doing:

alert('[' + xmlhttp.responseText +']');

in place of your if statement.

If the alerted value is not exactly

[<font color=green>Correct !</font>]

then you've got a problem. I suspect you'll get:

[<font color=green>Correct !</font>
]

or similar - in which case you need to modify your if statement as appropriate.

A better and less fragile approach would be something like this:

if(xmlhttp.responseText.indexof("Correct")>=0) {
 return true;
} else {
 return true;
}

or even better just do:

return (xmlhttp.responseText.indexof("Correct")>=0);
answered Dec 18, 2010 at 15:11
Sign up to request clarification or add additional context in comments.

Comments

1

Are you expecting isEmailValid() to return true or false? Because the way it's written it will return nothing. The nested function defined inside isValidEmail() returns true or false but that will get called asynchronously some time after isValidEmail() has finished executing. And it won't be called by by your code. It gets called by the browser so you'll likely never have a chance to examine the return value to check if it's true or false.

One way to change your code to accomplish the goal of having isValidEmail() return true or false is to make the XMLHttpRequest call synchronous, rather than asynchronous (SJAX instead of AJAX). That way isValidEmail() will block until it receives a response back from the server (or times out). Of course your user will be unable to do anything on the page while they wait for their email address to be validated. This may or may not be acceptable.

Also, as others have pointed out, your regular expressions and string matching may need a little tweaking but judging by the question, that's not specifically what you're asking about.

answered Dec 18, 2010 at 15:13

4 Comments

Good catch - I didn't spot he was returning from an asynchronous function. I'll +1 when I get more votes :)
ya i understand your point.And any idea to handle this async situation
Make the call synchronous, not asynchronous. You'll have to change the XMLHttpObject code.
im new in this thing can you advise me to how to change the getHTTPObject() function. code has attached to the post ...
0

I would suggest using a better stuffs in both PHP and javascript. Like, the PHP script could output the result in XML or JSON. And the Javascript, on the client side would parse the string according the format.

I suggest you have a look at the following links: For JSON (I personally prefer JSON to XML, and some ways JSON is much better than XML)

For XML, simply google, I am sure you will get many results.

Eg: in PHP:

$obj['result'] = 1;
$obj['color'] = 'green';
echo json_encode($obj);

in Javascript:

try{
 var result = JSON.parse(xmlhttp.responseText);
}catch(err){
 alert("...");
}
answered Dec 18, 2010 at 15:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.