DEV Community

loading...

jQuery Form multi submit preventDefault() ajax

Falah Al Fitri
I am Developer
Updated on ・1 min read

Happy Coding

https://stackoverflow.com/questions/16638181/targeting-multiple-forms-to-send-via-ajax-jquery/59319231#59319231
https://stackoverflow.com/questions/19182199/to-submit-a-form-among-multiple-forms-using-jquery-ajax#autocomment104839387

/* get all form and loop */
$( "form" ).each( function () {

    /* addEventListener onsubmit each form */
    $( this ).bind( "submit", function (event) {

        /* return false */
        event.preventDefault();

        /* formHTML element (object) */
        var formHTML = event.target;

        /* display each props of forms */
        console.log( formHTML );
        console.log( "form id: " + formHTML.id );
        console.log( "form method: " + formHTML.method );
        console.log( "form action: " + formHTML.action );

        /* ajax */
        $.ajax({

            method: formHTML.method,
            url: formHTML.action,

            data: $( this ).serialize(), // serializes the form's elements.

            success: function(result)
            {
                alert(result);
                console.log(result);
            }

        });          

    } );

});

Demo repl.it

Discussion (0)