DEV Community

loading...

jQuery Form multi submit preventDefault() ajax formData

antelove19 profile image Falah Al Fitri 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 );

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

        });          

    } );

});

Demo repl.it

Discussion (0)

pic
Editor guide