I need to write a function using jquery and ajax where at the click on the avatar, the user can choose a picture and upload a new one. Saving it in a folder in my website files.
So for the moment i have this html:
<img src="images/avatars/<?= $infos['Avatar']; ?>" onclick="setPicture()"
alt="avatar" class="rounded-circle clickable" width="150">
<form class="d-none" id="formAvatar" method="post" enctype="multipart/form-
data">
<input class="d-none" type="file" id="inputAvatar" name="inputAvatar" />
</form>
And here is my script:
function setPicture() {
$('#inputAvatar').trigger('click', function() { // So here i trigger a click on the input file when the user click on his profile picture. The input is not visible by default on the page.
let userfile = $('#inputAvatar').val();
if(userfile) { // here i want to check if a file has been selected but it doesn't seems to work
$('#formAvatar').submit(); // Here i submit the form if the previous condition is true
$("#formAvatar").on('submit',(function(e) { // Here if the form is submitted i send the picture to a php treatment page
e.preventDefault();
$.ajax({
type: 'POST',
url: 'traitements/traitement-profil.php',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
let errorWindow = document.getElementById('erreur');
errorWindow.className = "alert alert-danger my-5 text-center";
errorWindow.innerHTML = data;
}
});
})
)}
});
}
Can anyone help me please ?