Upload in Submit form AJAX

Asked

Viewed 624 times

0

I have a form where I send data through AJAX jQuery. However, I would also like to send a file. How do I add to my code?

var formData = {
    'titulo': $('input[name=titulo]').val(),
    'tipo'  : $('select[name=tipo]').val(),
    'dataa' : $('input[name=data]').val(),
    'desc'  : $('textarea[name=desc]').val()
};

// process the form
$.ajax({
    type        : 'POST',
    url         : 'processar.php',
    data        : formData,
    dataType    : 'json',
    encode      : true
})
  • None of these questions solved your problem?

1 answer

0

You could try something like :

HTML

<h1>jQuery Ajax submit Multipart form</h1>

<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
    <input type="text" name="extraField"/><br/><br/>
    <input type="file" name="files"/><br/><br/>
    <input type="file" name="files"/><br/><br/>
    <input type="submit" value="Submit" id="btnSubmit"/>
</form>

<h1>Ajax Post Result</h1>
<span id="result"></span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

</body>
</html>

JS

$(document).ready(function () {

    $("#btnSubmit").click(function (event) {

        //stop submit the form, we will post it manually.
        event.preventDefault();

        // Get form
        var form = $('#fileUploadForm')[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: "/api/upload/multi",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            success: function (data) {

                $("#result").text(data);
                console.log("SUCCESS : ", data);
                $("#btnSubmit").prop("disabled", false);

            },
            error: function (e) {

                $("#result").text(e.responseText);
                console.log("ERROR : ", e);
                $("#btnSubmit").prop("disabled", false);

            }
        });

    });

});

Source : https://www.mkyong.com/jquery/jquery-ajax-submit-a-multipart-form/

The secret here is to use new Formdata() to "retrieve form data" and set the parameter processData from the ajax request to FALSE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.