Skip to content
Advertisement

Ajax call from click event issue

Look at the HTML code below:

<div class="user-avatar-wrapper"> 
  <img class="profile-pic" src="/placeholder.png" alt="" />
  <div class="upload-button"></div>
  <input class="file-upload" type="file" accept="image/*"/>
</div>

Now I want to trigger the file upload and call to ajax on the click by .upload-button.

This is how I tried it in jQuery,

$(document).on('click', '.upload-button', function(e) {
  e.preventDefault();
  //$(".file-upload").click();
  $(this).next().trigger('click', function() {
    var $data = { 'title': 'Title', 'file': 'myfile' };
    $.ajax({
      type: 'POST',
      url: 'upload.php',
      data: $data,
        success: function(response) {     
      },
      error: function(response) {},
    });
  });
});

But, this code not working for me. That mean it didn’t send the ajax request.

Hope somebody may help me out.

Advertisement

Answer

I think you’re mixing up a trigger with an event handler.
When you click the div you should trigger a click on the file input but you don’t pass a callback there.
You want to set up a change handler for the file input to make an ajax request when the file is selected with a change event handler.

$(document).on('change', '.file-upload', function(e){
    var data = new FormData();
    data.append('title', 'Title');
    data.append('file', this.files[0]);
    $.ajax({
      type: 'POST',
      url: 'upload.php',
      data: data,
      processData: false,
      contentType: false,
      success: function(response) {     
      },
      error: function(response) {},
    });
    $(this).prev().html(`↑${this.files[0].name}`);
});
$(document).on('click', '.upload-button', function(e) {
  $(this).next().click();
});
.upload-button{
cursor:pointer;
}
.file-upload{
opacity:0.01
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="user-avatar-wrapper"> 
  <img class="profile-pic" src="/placeholder.png" alt="" />
  <div class="upload-button">↑</div>
  <input class="file-upload" type="file" accept="image/*"/>
</div>
<div class="user-avatar-wrapper"> 
  <img class="profile-pic" src="/placeholder.png" alt="" />
  <div class="upload-button">↑</div>
  <input class="file-upload" type="file" accept="image/*"/>
</div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement