As @javiertapia tells you, the solution is simpler. When, for example, a user edits his profile and this includes his avatar; by default this is shown in a section of preference encoded in base64:
$id = $_SESSION["user"]["id"];
// consulta
$data = array();
$row = $result->fetch_assoc();
$entry = array(
"name" => $row["name"],
"lastname" => $row["lastname"],
"email" => $row["email"],
"avatar" => base64_encode($row["avatar"])
);
array.push($data, $entry);
echo json_encode($data);
In the code above, the user information has been converted to an array. The image has been encoded from a base64 blob by means of base64_encode
and has been sent this information by JSON (it can be as an array and I send it to the view to iterate in this one).
Then, in the client you would get this JSON:
Note: In this example I use the new API for AJAX fetch
. You can use jQuery#ajax
or the classic XMLHttpRequest
. If you use this method be sure to include the polyfill in your HTML.
fetch('/profile')
.then(res => res.json())
.then(user => {
updateEditForm(user);
});
function updateEditForm (user) {
let form = document.getElementById('user-edit-form');
form.name.value = user.name;
form.lastname.value = user.lastname;
form.username.value = user.username;
form.email.value = user.email;
setPhoto(user.avatar);
}
function setPhoto (imgdata) {
let img = document.getElementById('avatar');
img.src = imagedata;
}
Now, how to know if the photo has been changed? Simple, creating an object FormData
and verifying if the key avatar
has a valid value. If you do not have it, that object's entry is deleted.
function updateUser (e) {
e.preventDefault();
let form = document.getElementById('user-edit-form');
let newData = new FormData(form);
// elimina la entrada 'avatar' si no se ha escodigo un archivo
if (!newData.get('avatar')) {
newData.delete('avatar');
}
fetch('/profile', {
method: 'POST',
body: newData
})
.then(() => {
alert('Perfil actualizado');
});
}
In PHP, you should only proceed to update with the data you have received.