Rajasekaran Raji
Rajasekaran Raji

Reputation: 74

Ajax Form Post and Validation Not Working

I am try to post data using Ajax and jquery form validation but its not works at first time of submit function with validation. Any Solutions?

$(document).ready(function() {
$("#myForm").validate();
});

(function($){
    function processForm( e ){
        $.ajax({
            url: 'post.php',
            dataType: 'text',
            type: 'post',
            contentType: 'application/x-www-form-urlencoded',
            data: $(this).serialize(),
            success: function( data, textStatus, jQxhr ){
                //$('#response pre').html( data );
                alert('scuss');
            },
            error: function( jqXhr, textStatus, errorThrown ){
                //console.log( errorThrown );
                alert('error');
            }
        });

            e.preventDefault();
    }

$('#myForm').submit(function(e){
e.preventDefault();
if(!$("#myForm").valid()) return; 
$('#myForm').submit( processForm ); 
}); 
})(jQuery);

Upvotes: 0

Views: 135

Answers (1)

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Why are you calling submit inside submit? Just call the function processForm in the else part as below:

$('#myForm').submit(function(e){
    e.preventDefault();
    if(!$(this).valid()) 
       return; 
    else
       processForm($(this));
}); 

No need to pass e to function as you are already preventing default action of form, instead pass the form itself.

function processForm(form){
     var $this=$(form);//cache the form
     $.ajax({
           url: 'post.php',
           dataType: 'text',
           type: 'post',
           contentType: 'application/x-www-form-urlencoded',
           data: $this.serialize(),
           success: function( data, textStatus, jQxhr ){
                //$('#response pre').html( data );
                alert('scuss');
           },
           error: function( jqXhr, textStatus, errorThrown ){
                //console.log( errorThrown );
                alert('error');
           }
      });
}

Upvotes: 1

Related Questions