开发者

I have a problem in AJAX

开发者 https://www.devze.com 2023-01-31 01:11 出处:网络
I have a problem with some of my validation code. Here it is. function isEmailValid(email) { if( email== \"\") {

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;开发者_StackOverflow社区
}
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.


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);


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.


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)

  • http://www.json.org/example.html

  • http://www.php.net/manual/en/function.json-encode.php

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("...");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消