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.
2
Answers
Your div is empty & doesn’t have any existence to run a function
Try the below code:
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.