Validation plugin addMethod with ajax

Validation plugin addMethod with ajax

Hello,

I am trying to use the addMethod to add a validation of duplicate username. The duplicate check is done with an AJAX call.

The php file called by AJAX returns 0 if the username does not exist in the database and 1 if it does.

The problem is I always get the error no matter what the AJAX call returns.
My code:
  1. jQuery.validator.addMethod("duplicate_username", function(value, element) {
            var duplicate = 0;
             $.ajax({
                     url: '/modules/user_management/ajax/check_duplicate_username.ajax.php?username='+$('#username').val(),
                     type: 'GET',
                     success: function (data) {
                         duplicate = data;
                     }
             });
            return this.optional(element) || duplicate == 1;
        }, "The username you entered is already used");









  1. $("#createUserForm").validate({
            debug: true,
            errorElement: 'span',
            errorClass: 'error',
            rules: {
                username: {
                    required: true,
                    duplicate_username: true
                },
                password: { required: true },
                email: { email: true }
            },
            messages: {
                username: {
                    required: "Please enter a username",
                    duplicate_username: "The username you entered is already used"
                },
                password: {
                    required: "Please enter a password"
                },
                email: "Please enter a valid email address"
            },
            submitHandler: function(form) {
                $(form).ajaxSubmit({
                    url: '/modules/user_management/ajax/create_user.ajax.php',
                    target: 'result',
                    beforeSubmit: function() {
                        $('.ajaxLoading').show();
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('.ajaxLoading').hide();
                        saved_dialog();
                    }
                });
            }
        });



































Can someone please help?