Im trying to submit a form that has a file input via ajax. I have a few important things that need to happen.
- The file input should be triggered by a button (done)
- The form should be submitted when a file has been selected (done)
- The page should NOT refresh and I should be able to check the result in the standard ajax fashion.
I have tried to do this myself, but nothing I find fits my needs.
The user needs to see a button like this, instead of the standard form input:
I have used the following code:
<form id="uploadProfilePictureForm" action="" method="post" enctype="multipart/form-data" style="display: none">
<input name="uploadProfilePicture" id="uploadProfilePicture" type="file" onchange="this.form.submit()" style="display: none;"/>
</form>
<a id="changeProfileButtonIcon" class="btn btn-info float-right mx-0 my-0">Change (in progress)</a>
<script>
$("#changeProfileButtonIcon").on('click', function(e){
e.preventDefault();
$("#uploadProfilePicture:hidden").trigger('click');
});
</script>
This opens the input correctly, and if I have the action set to my upload page, the image is uploaded when the select dialog is closed and then I just see a white page with my success message (as expected)
Because I don't want a page refresh I have attempted to do this via jQuery:
$("#uploadProfilePictureForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "/helpers/upload_image.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) // A function to be called if request succeeds
{
var a = 1;
}
});
}));
I placed a breakpoint on the line "preventDefault" and also on the "var a = 1" none of these get triggered and the page just refreshes.
Can anyone help me?
Thanks