开发者

jQuery ajax validate works partially

This is my code:

    $(function() {

        var name = $( "#name" ),
            email = $( "#email" ),
            password = $( "#password" ),
            allFields = $( [] ).add( name ).add( email ).add( password ),
            tips = $( ".validateTips" );

        function updateTips( t ) {
            tips
                .text( t )
                .addClass( "ui-state-highlight" );
            setTimeout(function() {
                tips.removeClass( "ui-state-highlight", 1500 );
            }, 500 );
        }

        function checkLength( o, n, min, max ) {
            if ( o.val().length > max || o.val().length < min ) {
                o.addClass( "ui-state-error" );
                updateTips( "Length of " + n + " must be between " +
                    min + " and " + max + "." );
                return false;
            } else {
                return true;
            }
        }

        function checkRegexp( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                updateTips( n );
                return false;
            } else {
                return true;
            }
        }

function ajaxValidate(type,fval,n) {
    //alert(type+" "+fval.val()+" "+n);
    $.ajax({
       type: "GET",
       url: "ajaxValidate.php",
       data: "type="+type+"&q="+escape(fval.val()),
       success: function(msg){
         if (msg != "") {
         fval.addClass( "ui-state-error" );
         updateTips( n );
             return false;
         }
         else {
             return true;
         }
       }
     });
}

        $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 540,
            width: 420,
            modal: true,
            buttons: {
                "Create an account": function() {
                    var bValid = true;
                    allFields.removeClass( "ui-state-error" );

                    bValid = bValid && checkLength( name, "username", 3, 16 );
                    bValid = bValid && checkLength( email, "email", 6, 80 );
                    bValid = bValid && checkLength( password, "password", 5, 开发者_开发技巧16 );
                    bValid = bValid && ajaxValidate("user", name,"Username is taken");
                    bValid = bValid && ajaxValidate("email", email,"Email address is taken");


                    bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                    // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                    bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. john.doe@pokermaps.org" );
                    bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                    if ( bValid ) {
                        $( "#users tbody" ).append( "<tr>" +
                            "<td>" + name.val() + "</td>" + 
                            "<td>" + email.val() + "</td>" + 
                            "<td>" + password.val() + "</td>" +
                        "</tr>" ); 

                        document.forms["regform"].submit();
                        $( this ).dialog( "close" );

                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }
        });

        $( "#create-user" )
            .button()
            .click(function() {
                $( "#dialog-form" ).dialog( "open" );
            });
    });

My problem is with the ajaxValidate function and the two lines in the code that calls that function.

For some strange reason, it only works one time, meaning, if you keep the first call to validate the user, it will do it properly but won't validate the email, but if you place the email validate call first, it will validate it but won't validate the user.

The rest of the validation script works, so if I comment out the two call lines, everything works perfectly.

The PHP script also works.

Why is that?

UPDATE::

Ok guys, I have changed the function a bit by unifying the validation requests, so now ajaxValidate looks like this:

function ajaxValidate(fval1,fval2,n) {
    //alert(type+" "+fval.val()+" "+n);
    $.ajax({
       type: "GET",
       url: "ajaxValidate.php",
       data: "?email="+escape(fval1.val())+"&user="+escape(fval2.val()),
       success: function(msg){
         alert(fval1.val());
         alert(msg);
       }
     });
}

The call to the function looks like this:

bValid = bValid && ajaxValidate(email, name ,"Email/User address is taken");

And ajaxValidate.php looks like this:

require_once('classes/db/conn.php');
$user = $_GET['user'];
$email = $_GET['email'];


$query_user = mysql_fetch_array(mysql_query("SELECT USR_ID FROM users WHERE USR_Username = '$user'"));

$query_email= mysql_fetch_array(mysql_query("SELECT USR_ID FROM users WHERE USR_Email = '$email'"));


echo("SELECT USR_ID FROM users WHERE USR_Email = " . $email);

Now, after I submit the form, I should be getting one alert with the email that was filled in, and one alert with the content of the ajax response which should be the sql query with the email from the $_GET var.

What i'm getting is, on the first alert I get the email address correctly, and on the second alert I'm getting the whole query, but without the email address. (SELECT USR_ID FROM users WHERE USR_Email =)

I'm going crazy, I can't figure this out!


I think the problem is that you're passing a string value for the data key when in fact it is expecting an object. E.g. -

jQuery.ajax({type:"GET", url:"/", data:"?bob=bob&carol=carol",success:function(){console.log(arguments.length);}})

Actually hits the URL - stackoverflow.com/?_=1295905818376&?bob=bob&carol=carol

Whereas -

jQuery.ajax({type:"GET", url:"/", data:{bob:"bob", carol:"carol"},success:function(){console.log(arguments.length);}})

Hits the URL - stackoverflow.com/?_=1295906023724&bob=bob&carol=carol

(the extra parameter that's turning up is a timestamp that jQuery adds to prevent the response being cached)

So I reckon if you change your code to the following it should give you the alerts you are expecting -

 $.ajax({
   type: "GET",
   url: "ajaxValidate.php",
   data: {email: fval1.val()), user:fval2.val()},
   success: function(msg){
     alert(fval1.val());
     alert(msg);
   }
 });

It's probably then worth bearing in mind that the code in the success callback function will be run at some point in the future and not at that point sequentially in the code. That means that you're probably going to have to rework your validation code to something of the form -

           "Create an account": function() {
                var bValid = true;
                allFields.removeClass( "ui-state-error" );

                bValid = bValid && checkLength( name, "username", 3, 16 );
                bValid = bValid && checkLength( email, "email", 6, 80 );
                bValid = bValid && checkLength( password, "password", 5, 16 );


                bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. john.doe@pokermaps.org" );
                bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
                var $this = $(this);
                $.ajax({
                  type: "GET",
                  url: "ajaxValidate.php",
                  data: "?email="+escape(fval1.val())+"&user="+escape(fval2.val()),
                  success: function(msg){
                    $( "#users tbody" ).append( "<tr>" +
                        "<td>" + name.val() + "</td>" + 
                        "<td>" + email.val() + "</td>" + 
                        "<td>" + password.val() + "</td>" +
                    "</tr>" ); 

                    document.forms["regform"].submit();
                    $this.dialog( "close" );
                  },
                });
            },

I've never used the dialog stuff before so I'm not sure what the plugin is expecting the function to return etc., but you're going to want a structure something more like that to support the async call.

Hope that helps,

Chris


Your ajaxValidate function doesn't return anything explicitly, so it returns undefined implicitly, which is then casted to boolean false.

To be able to return validation status from function you should make synchronous call to server side validator. Check out jQuery docs about making ajax request, you will need to set async property to false.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜