【发布时间】:2016-08-31 20:09:21
【问题描述】:
我想更新已登录我网站的用户的个人资料图片。 我使用 ajax、jquery、php 来更新数据,以便在不刷新页面的情况下更新数据。 此代码仅用于将图像上传到文件夹,但是当我使用此代码从数据库更新图像时,它仅将 null 发送到数据库。
jquery 和 ajax 脚本
$("#form-ava").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "../config.inc/upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview-ava").html(data).fadeIn();
$("#form-ava")[0].reset();
$("#hidden-list").hide();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
这是 php 语法 上传.php
<?php
require_once 'koneksi.php';
if($_POST)
{
$id_user= $_POST['id_user'];
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = '../images/ava/'; // upload directory
try {
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";
}
else
{
echo 'invalid';
}
$update = $db_con->prepare("UPDATE tb_users SET image=:img WHERE id_user=:id_user");
$update->bindparam(":id_user", $id_user);
$update->bindparam(":img", $image);
$update->execute();
$count = $update->rowCount();
if($count>0) {
echo "success";
}else {
echo "can't update!";
}
}
}catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
HTML 语法
<form id="form-ava" action="../config.inc/upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id_user" name="id_user" value="<?php echo $row->id_user;?>">
<input id="ava-img" type="file" name="image" value="<?php echo $row->image;?>"/>
<input id="button" type="submit" value="Simpan" name="update"></br>
<a href="#" class="btn btn-large btn-success" id="cancel-act"></i> Batal</a>
</form>
<div id="err"></div>
【问题讨论】:
-
我们不会为您编写代码...请尝试一下,然后我们可以帮助调试; )
-
@Webomatik 抱歉,我没有要求你编写代码。我只是请人告诉我为什么它不起作用...
-
@GrzegorzGajda 谢谢你,我会试试的..
-
告诉我们当你运行你的代码时会发生什么,你得到了什么错误,什么行为是错误的,等等。