Look at the HTML code below:
<div >
<img src="/placeholder.png" alt="" />
<div ></div>
<input 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.
CodePudding user response:
Your div is empty & doesn't have any existence to run a function Try the below code:
<div > </div>
CodePudding user response:
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) {},
});
});
$(document).on('click', '.upload-button', function(e) {
$(".file-upload").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 >
<img src="/placeholder.png" alt="" />
<div >↑</div>
<input type="file" accept="image/*"/>
</div>