I am trying to post some data into server using ajax. I am stuck on uploading image, I don't know where my mistake is. Can any one please suggest how can I fix this?
Below is my script and php code.
$("#submit").click(function() {
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
var name = $("#first_name").val();
var country = $("#country").val();
var city = $("#city").val();
$.ajax({
url: 'personaliseService.php?name=' + name + '&country=' + country + '&city=' + city,
dataType: 'json',
processData: false,
contentType: false,
data: formData,
//data: new FormData(), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
success: function(response) {
console.log(response);
},
error: function(error) {
alert("Yes");
console.log(error);
}
});
});
<?php
include("config.php");
$name = $_REQUEST['name'];
$country = $_REQUEST['country'];
$city = $_REQUEST['city'];
$image = $_FILES['image']['name'];
$sourcePath = $_FILES['image']['tmp_name'];
$targetPath = "uploads/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath) ; // Moving Uploaded file
$sql = "INSERT into personalise (name, country, city, image) VALUES ('$name', '$country', '$city', '$image')";
$sqlQuery = mysqli_query($conn, $sql);
if(mysqli_insert_id($conn) > 0){
$insertValue = array("response" => "Data Inserted Successfully");
echo '{"response": '.json_encode($insertValue).', "success": true}';
}else{
echo '{"response": '.json_encode($insertValue).', "success": false}';
}
?>