我正在尝试使用jQuery和ajax上传文件。但我的代码不起作用。所选文件未上传。
// jQuery的
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#upload'); // submit button
var alert = $('.alert1'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'update_profile_pic.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
$('#img1').show();
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
$('#img1').hide();
//window.location='update_profile.php';
},
error: function(e) {
console.log(e);
}
});
});
});
// html代码
<form action="" method="post" enctype="multipart/form-data" id="form1">
<p><input type="file" class="textbox_black" name="profile_pic" required /></p>
<p><input type="submit" name="update" value="Upload" class="button" id="upload" /></p>
</form>
// update_profile_pic.php
$profile_pic= $_FILES["profile_pic"]["name"];
$target_path= "uploads/profile_pic/";
$target_path= $target_path.basename($profile_pic);
if($profile_pic == "")
{
echo "* Select profile pic!";
}
else
{
if(move_uploaded_file($_FILES['profile_pic']['tmp_name'], $target_path))
{
$result = mysql_query("UPDATE signup SET profile_pic='$target_path' WHERE username='$username'") or die(mysql_error());
if($result)
{
echo "* Profile pic updated";
}
else
{
echo "Something went wrong. Tryagain later!";
}
}
}
我的编码是否有任何错误。有没有办法解决我的问题。我已经尝试了很多来解决这个问题,但没有结果。