I am writting a client database system for my company. Not much fancy stuff, but it does what it should. Now that all the basic "text" stuff is done I want to add some filemanagement into it.
I have several forms which get send to the backend with ajax and then written into the db in the model.
Some of these forms are planned to have a document file upload.
Is there a way to handle normal value submits and a file submit with AJAX ?
Let me give you a FORM example:
<form action="SOMEPATH/LOGIC_FILE.php" action="POST" enctype= multipart/form-data>
<label for="name">
<input type="text" id="name" name="name" />
</label>
<label for="somethingElse">
<input type="text" id="somethingElse" name="somethingElse" />
</label>
<label for="fileUpload">
<input type="file" />
</label>
</form>
AJAX example:
var name = $('#name').val();
var somethingElse = $('#somethingElse').val();
var dataArr = { 'name':name, 'somethingElse':somethingElse};
MYELEMENT.click(function(e){
e.preventEventDefault();
$.ajax({
url: "PATH/logic/logic_update_client_allg.php",
type: "POST",
data: allgArray,
success: function(dataArr){
// works
},
error: function(){
// doesnt work
}
});
}
Thats how I handle my INPUT VALUE submit
How can I proceed to also upload a file with this form
Thank you
Use jquery malsup form plugin to send files using AJAX
https://github.com/malsup/form
For ajax uploads you need to use
xmlHttpRequest
which is already available in thejQuery.ajax()
method, but with use ofFormData
.If you are not targeting IE legacy versions, like 7,8 you can use
FormData
. One thing to be noticed that you have to setcontentType, processData
tofalse
.See the example below: