jQuery Ajax Form Submit FormData Example

jQuery Ajax form submit with multipart form or FormData; Through this tutorial, i am going to show you how to submit form or form data using the jquery ajax.

AJAX:- AJAX (asynchronous JavaScript and XML) is the art of exchanging data with a server and updating parts of a web page – without reloading the entire page.

How To Submit AJAX Forms with JQuery

  • Create HTML Form
  • Implement jQuery Ajax Code for Submit Form

Create HTML Form

Create an HTML form with multiple fields; as shown below:

<!DOCTYPE html>
<html>
<title>jQuery Ajax Form Submit with FormData Example</title>
<body>
<h1>jQuery Ajax Form Submit with FormData Example</h1>
<form method="POST" enctype="multipart/form-data" id="myform">
    <input type="text" name="title"/><br/><br/>
    <input type="file" name="files"/><br/><br/>
    <input type="submit" value="Submit" id="btnSubmit"/>
</form>
<h1>jQuery Ajax Post Form Result</h1>
<span id="output"></span>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> 
</body>
</html>

Implement jQuery Ajax Code for Submit Form

Implement jQuery ajax code for send or submit form data using jquery ajax; as shown below:

$(document).ready(function () {
    $("#btnSubmit").click(function (event) {
        //stop submit the form, we will post it manually.
        event.preventDefault();
        // Get form
        var form = $('#myform')[0];
       // Create an FormData object 
        var data = new FormData(form);
       // If you want to add an extra field for the FormData
        data.append("CustomField", "This is some extra data, testing");
       // disabled the submit button
        $("#btnSubmit").prop("disabled", true);
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "/upload.php",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 800000,
            success: function (data) {
                $("#output").text(data);
                console.log("SUCCESS : ", data);
                $("#btnSubmit").prop("disabled", false);
            },
            error: function (e) {
                $("#output").text(e.responseText);
                console.log("ERROR : ", e);
                $("#btnSubmit").prop("disabled", false);
            }
        });
    });
});

Conclusion

jQuery Ajax form submit with multipart form or FormData; Through this tutorial, You have learned how to submit form or form data using the jquery ajax.

Recommended jQuery Tutorials

Leave a Comment