The-Evil-Fox
The-Evil-Fox

Reputation: 111

Upload a file(picture) using ajax and jquery

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 ?

Upvotes: 0

Views: 539

Answers (1)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

[1] You'll not get a value with .trigger with input file type you need to use change

[2] No need to use a function . you can use class avatar for the image .. And make the events separated then trigger it in it's place

  • Form submit
  • Input File change
  • The image click to trigger the input file click

$("#formAvatar").on('submit', function(e) { // Here if the form is submitted i send the picture to a php treatment page

  e.preventDefault();
  console.log('submitted');
 /* $.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;

      }

  });*/

});

$('#inputAvatar').on('change', 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 = $(this).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
    }
}); // close the change event
  
$('.avatar').on('click' , function(){ // trigger the input file click
  $('#inputAvatar').click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="images/avatars/<?= $infos['Avatar']; ?>"  alt="avatar" class="avatar 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>

Upvotes: 1

Related Questions