我正在使用CodeIgniter,ajax和jquery验证 . 我正在上传 Profiles 图片,但它不起作用 .
如果我上传没有jquery验证的图像然后它正在工作但是使用jquery验证,它不起作用 . 它显示If条件
if ($this - > form_validation - > run() == FALSE) {
echo "Not working";
}
它's not sending the image name from ajax to controller. I added the server side validation and it'显示错误 "The Profile Pic field is required."
你能帮我解决这个问题吗?
View
<form action="#" method="post" id="edit_Memberdetails" enctype="multipart/form-data">
<input type="file" name="profile_pic" id="profile_pic">
<?php echo form_error('profile_pic'); ?>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
AJAX
$(document).ready(function() {
$("#edit_Memberdetails").validate({
// Specify the validation rules
rules: {
profile_pic: {
required: true,
extension: "jpg,jpeg,png"
}
},
submitHandler: function(form) {
var formData = new FormData(form);
$.ajax({
url: "<?php echo base_url('Member_controller/edit_Memberdetails');?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data) {
alert("Added successfully");
setTimeout(function() { // wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 1000);
},
}); // AJAX Get Jquery statment
}
});
});
Controller
public function edit_Memberdetails() {
$this - > form_validation - > set_error_delimiters('<div class="error">', '</div>');
$this - > form_validation - > set_rules('profile_pic', 'Profile Pic', 'required');
if ($this - > form_validation - > run() == FALSE) {
echo "Not working";
} else {
$config = [
'upload_path' => './uploads/images',
'allowed_types' => 'jpg|png|jpeg',
'file_name' => uniqid().time().date("dmy")
];
print_r($config);
$this - > load - > library('upload', $config);
if ($this - > upload - > do_upload('profile_pic')) {
$profile_pic_set = $this - > upload - > data('file_name');
}
$data = array(
'profile_pic' => $profile_pic_set
);
$secure_data = $this - > security - > xss_clean($data);
if ($secure_data) {
$this - > db - > where('customer_id', $this - > session - > userdata['login_session']['custid']);
$this - > db - > set($secure_data);
$this - > db - > update('members', $secure_data);
$this - > session - > set_flashdata('success', "recode added");
} else {
$this - > session - > set_flashdata('error', "Sometning wrong! please check the internet connection and try again");
}
// redirect("Member_controller/member_dashboard");//calling employee register
}
}
2 回答
将图像附加到表单数据,例如:
full example here
要通过ajax上传图像,您必须手动将图像附加到
FormData
,因此请在submitHandler:
中将您的代码稍微更改一下文件上传数据未存储在 $_POST array 中,因此无法使用CodeIgniter的 form_validation library 进行验证 . 使用 $_FILES array 以及 Controller 中的更改表单验证规则,PHP可以使用文件上载:
对此: