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
1 Answer
Reset to default 0Let 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
版权声明:本文标题:Problem when sending file via ajax 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742220324a2435333.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论