Search code examples
ajaxformsinputchildren

Automate AJAXed forms with Jquery


I want to improve my website and figured out a good way to do it was by submitting forms via AJAX. But, I have so many forms that it would be inpractical to do $('#formx').submit(). I was wondering if there was a way to do this automatically by making an universal markup like;

<form class="ajax_form" meta-submit="ajax/pagename.php">
 <input type="text" name="inputx" value="x_value">
 <input type="text" name="inputy" value="y_value">
</form>

And have this submit to ajax/pagename.php, where it automatically includes inputx and inputy? This would not only save me a lot of time but also a lot of lines of code to be written.

First question so I hope it's not a stupid one :)


Solution

  • Something like this should work for all forms. It uses jQuery - is this available in your project? This specific code chunk hasn't been tested per say, but I use this method all the time. It is a wonderful time saver. Notice I changed meta-submit to data-submit so that its value can be fetched using $('.elemenet_class').data('submit');

    HTML

    <!-- NOTE: All Form items must have a unique 'name' attribute -->
    <form action="javascript:void(0);" class="ajax_form" data-submit="ajax/pagename.php">
        <input type="text" name="inputx" value="x_value">
        <input type="text" name="inputy" value="y_value">
    
        <input type="submit" value="go" />
    </form>
    

    JavaScript

    $('.ajax_form').submit(function(e){
        var path = $(this).attr('data-submit'); //Path to Action
        var data = $(this).serialize();    //Form Data
        $.post(path, {data:data}, function(obj){
    
        });
        return false;
    })
    

    PHP

    //DEBUGGING CODE
    //var_dump($_POST);
    //die(null);
    
    $data = $_POST['data'];
    $inputx = $data['inputx'];
    $inputy = $data['inputy'];