Skip to content Skip to sidebar Skip to footer

Submit Form Via Ajax In Jquery

I am using following jQuery code to submit a form via AJAX. jQuery('form.AjaxForm').submit( function() { $.ajax({ url : $(this).attr('action'),

Solution 1:

If using jQuery 1.7+ you could try using .on() to delegate the event and bind to all future forms with the same class. Try finding the closest parent that is not inserted dynamicly instead of $(document).

$(document).on('submit', 'form.AjaxForm', function() {            
        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                         alert('Submitted');
            },
            error   : function( xhr, err ) {
                         alert('Error');     
            }
        });    
        returnfalse;
    });

Solution 2:

You can't attach handlers directly to html that doesn't exist

There are 2 ways to handle it.

Bind the handlers within success callback of ajax.

    $(formParentSelector).load(formFileUrl, function() {
        /* within this success callback the new html exists and can run code*/AjaxForm();
    });

functionAjaxForm(){
    jQuery('form.AjaxForm').submit( function() {            
        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                        alert('Submitted');
                      },
            error   : function( xhr, err ) {
                        alert('Error');     
                      }
        });    

                                             })
 }

The other way is to delegate the handler to a higher level in the document so it is avalibale for future matching elements

jQuery(document).on('submit','form.AjaxForm').submit( function() {            
        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                        alert('Submitted');
                      },
            error   : function( xhr, err ) {
                        alert('Error');     
                      }
        });    

                                             })

Post a Comment for "Submit Form Via Ajax In Jquery"