jQuery Form multi submit preventDefault() ajax formData

antelove19

Falah Al Fitri

Posted on December 13, 2019

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

💖 💪 🙅 🚩
antelove19
Falah Al Fitri

Posted on December 13, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related