Ajax for multiple form

Updated at 23-Aug-2021, By samar

Ajax for multiple form

We will use programming in this lesson to attempt to solve the "Ajax for multiple form".

You can use a single ajax function to submit the multiple forms in HTML. You have to use a class for the submit button and the submit button should be inside the HTML form.
  • Dynamically get the form action url, method, data and call ajax on click using jQuery

    <form action="/post-ajax" method="POST">
      	<input type="submit" class="submit-form" value="submit" />
    </form>
    
    <form action="/post-ajax-2" method="POST">
      	<input type="submit" class="submit-form" value="submit" />
    </form>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    
    $(document).ready(function(){
        $('.submit-form').on('click', function(e){
            e.preventDefault();
            let form =  $(this).closest('form');
            let formActionUrl = form.attr('action');
            let type = form.attr('method');
            let formData = form.serialize();
            $.ajax({
                url: formActionUrl,
                type: type,
                data: formData,
                success: function(response){
                    console.log(response);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log(xhr.status);
                    console.log(thrownError);
                }
            });
        });
    });
    </script>
    

    This code snippet helps you to get the form attribute values and call ajax dynamically without any changes in javascript code. It will help you to submit multiple forms using the same ajax method.

Back to code snippet queries related jquery