DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on • Updated on

jQuery Form multi submit preventDefault() ajax


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);
            }

        });          

    } );

});
Enter fullscreen mode Exit fullscreen mode

Demo repl.it

Top comments (0)