Problem when sending file via ajax

I am trying to send a file via ajax but I get a 400 bad request error.
My code

data.coverQuestions.medicalMalpractice.file = docFile.prop('files')[0];

$.ajax({
url: '/wp-admin/admin-ajax.php',
method: 'post',
data: {
  action: 'insurance_form_data',
  data,
},
contentType: false,
processData: false,
success (res){
    console.log(res);
}
});

If remove the parameters and do not send files, then in this case it is successfully sent.

contentType: false processData: false

What could be the problem?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Let say you have a form:

<form name="post" id="post-form" action="" method="post" enctype="multipart/form-data">
    <input type="text" name="first_name">
    <input type="text" name="last_name">
    <input id="file" type="file" name="featured_image">
</form>

Now you have to pass the FormData object to ‘data’ parameter in ajax

jQuery(document).ready(function($) {
    $('#post-form').submit(function(e) {
        e.preventDefault();
        var form = $(this);

        file_data = $('#file').prop('files')[0]; //get the file
        form_data = new FormData(); //form_data is a FormData() object 
        form_data.append('featured_image', file_data); //append the file in form_data object
        form_data.append('action', 'insurance_form_data'); // your wordpress function name
        form_data.append('post_data', form.serialize()); // e.g. other form data such as first_name, last_name will be stored as serialized

        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            contentType: false,
            processData: false,
            data: form_data,
            success: function(response) {
                console.log(response);
            },
            error: function(xhr, status, error) {
                console.log(error);
            }
        });
    });

});

Now in PHP file you can test data as:

function insurance_form_data() {
    print_r($_POST);
    print_r($_FILES);
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x