I am trying to upload the file with the help of ajax, but some reason its not working properly I do not know what is the reason for that. this is my html and jquery and ajax code:
<!DOCTYPE html>
<html>
<title>insert data and upload image with ajax</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#d').click(function() {
var name = $('#a').val();
var designation = $('#b').val();
var fdata = new FormData();
var files = $ ('#c' )[0].files[0];
fdata.append( 'file', files );
$.ajax({
type: "POST",
url: "c3.php",
data: {name: name, des: designation, file1: fdata},
contentType: false,
cache: false,
processData: false,
success: function(result) {
alert(result);
}
});
});
});
</script>
</head>
<body>
<form method = "POST" enctype = "multipart/form-data">
<label for = "a"> name </label><br>
<input type = "name" id = "a"><br>
<label for = "b"> designation </label><br>
<input type = "text" id = "b"><br>
<label for = "c"> profile photo </label><br>
<input type = "file" id = "c"><br>
<input type = "button" id="d" value = "submit"><br>
</form>
</body>
</html>
and this is my php code:
<?php
$a = $_POST["name"];
$b= $_POST["des"];
$target_folder = "image/";
$target_path = $target_folder.basename($_FILES['file1']['name']);
if(move_uploaded_file($_FILES['file1']['tmp_name'], $target_path)){
$c = $target_path;
} else {
exit("upload failed");
}
$connect = mysqli_connect("localhost:3307", "root", "", "hello");
$sql = "insert into test(name, work, path) values ('$a', '$b', '$c');";
$result = mysqli_query($connect, $sql);
if($result) {
echo "uploaded the file and inserted the data successfully.";
} else {
echo "failed";
}
?>
please check my jquery and ajax code and php code and tell me that, what are the mistakes I did and what is the solution for that. thank you