DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on • Updated on

jQuery Form multi submit preventDefault() ajax formData


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

        /* using formData */
        var formData = new FormData( formHTML );
        console.log( formData );

        /* ajax */
        $.ajax({

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

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

            /*
                result type data
                JSON.parse(data)
                http://api.jquery.com/jQuery.ajax/
            */
            dataType: "HTML",

            cache: false,

            /* upload */
            contentType: false, // formData with $_POST or $_FILES in server (PHP)
            processData: false,

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

        });          

    } );

});
Enter fullscreen mode Exit fullscreen mode

Demo repl.it

Oldest comments (0)