我有这个表单来更改用户的个人资料照片。我试图在点击当前图片时更改图片并从用户文件系统中选择
形式:
<form id="changeProfilePicForm" action="<?=base_url()?>user/change_profile_pic" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<div data-content="Click To update" class="image" id="profile-image">
<input id="profile-image-upload" class="hidden" name="image" type="file" accept="image/x-png, image/gif, image/jpeg">
<?if(strlen($user['image'])){?>
<img src="<?=base_url().'uploads/profile/'.$user['image']?>" class="img-circle" alt="user profile pic" height="125px" width="125px">
<?}else{?>
<img src="<?=base_url()?>includes/img/avtar.png" class="img-circle" alt="user profile pic" height="125px" width="125px">
<?}?>
<input type="submit" class="hidden">
</div>
</form>
Javascript:
$("#changeProfilePicForm").on('submit',(function(e){
e.preventDefault();
var $form = $( this );
$.ajax({
url: $form.attr( 'action' ),
type: "POST",
data: new FormData($form),
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
}));
document.getElementById('profile-image').onclick = function() {
document.getElementById('profile-image-upload').click();
};
document.getElementById('profile-image-upload').onchange = function(){
document.getElementById('changeProfilePicForm').submit();
};
PHP控制器:
public function change_profile_pic()
{
$user_id = $this->session->user_id;
$image = $this->uploadimage();
if(strlen($image)){
$user_data['image'] = $image;
$updated = $this->user_model->update_user($user_id, $user_data);
$data['response'] = 1;
$data['image'] = $image;
// redirect(base_url()."user");
echo json_encode($data);
}else{
$data['response'] = 0;
$data['message'] = "error";
echo json_encode($data);
}
//redirect(base_url()."user");
}
我面临的问题是,表单不是通过ajax提交的。它是以简单形式提交的目录。我无法弄清楚代码的错误,因为图片是在简单的表单提交上传的。事件绑定有什么问题,或者我在这里遗漏了什么?
答案 0 :(得分:1)
致电时
var url="/relativeDir1/relativeDir2";
var pathModule = require("path");
var path = pathModule.resolve(path.join(__dirname, url));
document.getElementById('changeProfilePicForm').submit();
事件未被触发。尝试
submit
编辑。摆脱html中的表格:
$('#changeProfilePicForm').trigger('submit');
JS:
<input type="file" id="image">
答案 1 :(得分:0)
我相信FormData需要原生表单元素$form[0]
,而不是jQuery表单元素$form
。
$("#changeProfilePicForm").submit(function (e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr('action'),
type: "POST",
data: new FormData($form[0]),
contentType: false,
cache: false,
processData: false,
success: function (data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
}));