views:

43

answers:

3

I want to code a single js/jquery function for all forms submit events in my application.

Currently I am hardcoding on 3 locations like that and it is working but I have to create a function for each form separately:

jQuery('#myForm').live('submit',function(event) { // #myForm hardcoded here
    $.ajax({
        url: 'one.php', // one.php hardcoded here
        type: 'POST',
        data: $('#myForm').serialize(), // #myForm hardcoded here
        success: function( data ) {
            alert(data);
        }
    });
    return false;
});

Thanks

+2  A: 
  • You can probably replace $('#myForm') by $('form') or something else which matches all forms.
  • one.php is probably the action attribute on the form, or $('form').attr('action').
Sjoerd
+3  A: 
jQuery('form').live('submit',function(event) {
    $.ajax({
        url: $(this).attr('action'),
        type: 'POST',
        data: $(this).serialize(),
        success: function( data ) {
            alert(data);
        }
    });
    return false;
});
js1568
A: 

You could assign a common class to each form to use as a selector, and then leverage jQuery's .each() function to attach your function to the submit event. Therefore it would be something similar to:

jQuery('.form').each().live('submit',function(event) { ... } ); 
GotDibbs