我正在尝试使用php上传个人资料图片并将文件名保存在数据库中。没有ajax,我的脚本工作文件,但是当我尝试使用ajax方法保存数据时,我的意思是没有重新加载页面,它显示error
我的脚本
$(document).ready(function(){
$('#uploadImage').submit(function(e) {
e.preventDefault();
uploadImage();
});
});
function uploadImage(){
var image = $("#employee-image").val();
$.ajax({
type: "POST",
url: "upload-file.php",
data: "file_name=" + image,
success:function(response){
console.log(data);
$('#uploadImage')[0].reset();
//show the success message
$('#done').slideDown().html(response); ;
setTimeout(function(){
$('#done').slideUp();
}, 3000);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
表格
<form id="uploadImage" method="post" enctype="multipart/form-data">
<input type="file" id="employee-image" name="employee-image">
<input type="submit" name="submit" value="Upload">
</form>
PHP
<?php
// Include the database configuration file
include 'include/db.php';
$statusMsg = '';
// File upload path uploads/profile-pic/
$targetDir = "uploads/employee-uploads/";
$fileName = basename($_FILES["employee-image"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["employee-image"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["employee-image"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$sql = "INSERT into employee_image (file_name, uploaded_on) VALUES ('".$fileName."', NOW())";
$insert = mysqli_query($GLOBALS["___mysqli_ston"], $sql) or die(mysqli_error($GLOBALS["___mysqli_ston"]));
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
// Display status message
echo $statusMsg;
?>