admin管理员组

文章数量:1327945

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?

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?

Share Improve this question asked Jul 30, 2020 at 15:24 PavelPavel 1133 bronze badges 1
  • There may be legal issues with submitting medical records and insurance data into a WP site, especially in the EU and UK, that data needs to be securely held and storing it in an unencrypted custom table or posts may not be enough – Tom J Nowell Commented Jul 30, 2020 at 15:55
Add a comment  | 

1 Answer 1

Reset to default 0

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

本文标签: Problem when sending file via ajax