Look at the HTML code below:
JavaScript
x
6
1
<div class="user-avatar-wrapper">
2
<img class="profile-pic" src="/placeholder.png" alt="" />
3
<div class="upload-button"></div>
4
<input class="file-upload" type="file" accept="image/*"/>
5
</div>
6
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,
JavaScript
1
16
16
1
$(document).on('click', '.upload-button', function(e) {
2
e.preventDefault();
3
//$(".file-upload").click();
4
$(this).next().trigger('click', function() {
5
var $data = { 'title': 'Title', 'file': 'myfile' };
6
$.ajax({
7
type: 'POST',
8
url: 'upload.php',
9
data: $data,
10
success: function(response) {
11
},
12
error: function(response) {},
13
});
14
});
15
});
16
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.
JavaScript
1
19
19
1
$(document).on('change', '.file-upload', function(e){
2
var data = new FormData();
3
data.append('title', 'Title');
4
data.append('file', this.files[0]);
5
$.ajax({
6
type: 'POST',
7
url: 'upload.php',
8
data: data,
9
processData: false,
10
contentType: false,
11
success: function(response) {
12
},
13
error: function(response) {},
14
});
15
$(this).prev().html(`↑${this.files[0].name}`);
16
});
17
$(document).on('click', '.upload-button', function(e) {
18
$(this).next().click();
19
});
JavaScript
1
6
1
.upload-button{
2
cursor:pointer;
3
}
4
.file-upload{
5
opacity:0.01
6
}
JavaScript
1
11
11
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div class="user-avatar-wrapper">
3
<img class="profile-pic" src="/placeholder.png" alt="" />
4
<div class="upload-button">↑</div>
5
<input class="file-upload" type="file" accept="image/*"/>
6
</div>
7
<div class="user-avatar-wrapper">
8
<img class="profile-pic" src="/placeholder.png" alt="" />
9
<div class="upload-button">↑</div>
10
<input class="file-upload" type="file" accept="image/*"/>
11
</div>