I want to save an image in my database as a BLOB file using jquery, Ajax and PHP. I can upload it and display it in the form (if it is inserted manually in the database). However, when I change it on the form, the new image is well displayed but when I click on save it is not saved in the database. I did not find any solution here using jquery, Ajax and PHP, and storing the whole image in the database.
Here is a part of my HTML code (Content/users.php) :
<img src="images/defaultprofile.png" id="photoUserUpload"
name="image" onClick="triggerClick()" />
<input type="file"name="profileImage" id="profileImage" style="display:
none;" accept=".jpg, .png" onchange="displayImage(this)" />
</div>
<div>
<button id="saveTechItem" class="btn btn-primary saveTechItem">Save</button></div>
Here is a part of my js code (Data_Scripts/users.js):
$(document).on("click", ".saveItem", function() {
if (validateForm()) {
addOrUpdateItem();
}
});
function addOrUpdateItem(event) {
var itemId = $("#userId").val();
var fullName = $("#txtUserName").val();
var pic=$("#photoUserUpload").attr('src');
alert (pic);
//I tried also to append the file before submit
var file=new FormData();
file.append('file', file2);
//alert (file2);
var itemData = {
id: itemId,
postType: 'addOrUpdate',
fullName: fullName,
pic:pic
};
$.ajax({
url: 'data_ajax/users.php',
data: itemData,
type: "POST",
cache: false,
success: function(data) {
location.reload();
},
error: function(e) {
alert("error while trying to add or update user!");
}
});
}
Here is a part of my PHP code (DataAjax/user.php):
if (isset($_POST['id'])) {
$postType = $_POST['postType'];
if ($postType == "addOrUpdate") {
$Id = $_POST['id'];
$FullName = $_POST['userName'];
$pic = base64_encode(file_get_contents($_POST['pic']));
$data = new Data();
$db = $data->dataHandler();
$query = "INSERT INTO Users (`id`, `fullname`, `image`)
values ('$Id', '$FullName', '$pic')";
$db->query($query);
}
}