【发布时间】:2018-08-27 15:32:19
【问题描述】:
我正在使用 CodeIgniter。我正在尝试在 jquery 验证后使用 AJAX 上传图像,但它不起作用。如果字段为空,则 Jquery 验证正在工作。填写完所有字段并单击提交按钮后,我的页面刷新了。它没有调用控制器。
你能帮帮我吗?
$("#primary").validate({
errorElement: 'div',
rules: {
first_name: {
required: true,
alphabets: true,
minlength: 3
},
last_name: {
alphabets: true
},
profile_pic: {
extension: "png|jpeg|jpg|gif"
},
},
messages: {
profile_pic: {
extension: "Only PNG , JPEG , JPG, GIF File Allowed",
},
},
submitHandler: function(form)
{
var formData = new FormData(this);
$.ajax({
url: baseUrl + "/AddMember/addMembers",
type: 'POST',
//data: $('#primary').serialize(),
data:formData,
dataType: 'json',
success: function(data)
{
if (data.error == "true")
{
//success message
}
else {
//error message
}
}
});
}
});
控制器代码
$config=['upload_path' =>'./uploads/images',
'allowed_types' =>'gif|jpg|png|jpeg',
'file_name' =>uniqid().time().date("dmy")
];
if ($this->upload->do_upload('profile_pic'))
{
$profile_pic_set = $this->upload->data('file_name');
}
else{$profile_pic_set = "";//set empty value if user not uploading any image
}
$this->load->library('upload', $config);
$data = array(
'first_name' => trim($this->input->post('first_name')),
'last_name' => trim($this->input->post('last_name')),
'profile_pic' => $profile_pic_set
);
print_r($data); //here I am getting profile_pic empty.
html
<?php echo form_open_multipart('','id="primary"'); ?>
<input type="text" name="first_name" id="first_name" class="form-control" placeholder="First Name">
<input type="text" name="last_name" id="last_name" class="form-control" placeholder="Last Name">
<input type="file" name="profile_pic" id="file_upload">
<button type="submit" class="btn btn-primary btn_new">Submit</button>
<?php echo form_close(); ?>
【问题讨论】:
-
在名为
filesize或alphabets的jQuery Validate 插件中没有这样的规则。如果这些是自定义规则,那么您应该让我们知道并显示代码。 -
哦!对不起我的不好。我会删除它
-
如果页面正在刷新,那么您的 JavaScript 可能由于错误而无法工作。检查浏览器的 JavaScript 控制台是否有错误。检查在屏幕刷新之间保存控制台错误消息的设置。
-
您没有显示足够的代码来重现任何内容。您用
HTML5标记了这个问题,但它与HTML 无关。表单的相关 HTML 标记在哪里?对于上传文件,您需要form上的enctype="multipart/form-data"属性。 -
@Sparky,是的,没错,我在表单标签中使用了 enctype="multipart/form-data"。我收到错误 TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.[了解更多] 我在 var formData = new FormData(this); 中收到错误这一行
标签: php jquery jquery-validate codeigniter-3