bikey77
bikey77

Reputation: 6672

jQuery validation followed by Ajax post

I'm trying to combine jQuery validation plugin with Ajax post. This is my code:

PHP form:

<form id="newsletter_form" method="post">
    <input name="newsletteremail" type="text" id="newsletteremail" class="required email">
    <input name="Signup" type="submit" class="formsm" id="Signup" value="Signup">
    <div id="emailerrormessage"></div>
</form>

JQuery:

$('#newsletter_form').validate({
            rules: { 
                email: {required:true, email:true}
            },
            submitHandler: function(form) {
                $.ajax({
                    data: $(this).serialize(),
                    type: "POST",
                    url: "includes/ajax.php?action=newsletter", 
                    contentType: "application/x-www-form-urlencoded; iso-8859-7",
                    dataType: 'json',
                    success: function(response, textStatus, jqXHR) {
                        if(response.status == 'error'){

                            $("#newsletteremail").removeClass().addClass('ajaxerror');
                        } else {
                                                        $("#newsletteremail").removeClass();                            
                        }
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        $("#emailerrormessage").addClass('ajaxsuccess').html(xhr.responseText).show();
                    }
                });
                return false;
            }
        });

Before using validate() the form would submit fine. After adding the validate() code, the validation works, the form is being submitted (I receive a 200 OK response) but the values being submitted are null. What am I doing wring here?

Upvotes: 0

Views: 4429

Answers (2)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

this refers to the validator object that you're applying to the form, so change:

data: $(this).serialize(),

to

data: $(form).serialize(),

Upvotes: 1

Dipesh Parmar
Dipesh Parmar

Reputation: 27354

Use jQuery.form plugin and try it as below,

submitHandler: function(form)
{
    jQuery(form).ajaxSubmit(
    {
        dataType : 'json',
        beforeSend : function(arr, $form, options)
        {

        },
        success : function(msg)
        {
            return false;
        }
    });
}

Upvotes: 0

Related Questions