Reputation: 904
<form id="uploadForm" enctype="multipart/form-data" action="http://localhost:1337/ad/upload" method="post" name="uploadForm" novalidate>
<input type="file" name="userPhoto" id="userPhoto" />
<input type="submit" value="submit" id="uploadImage" />
</form>
This is my html form which accepts an image as file inout, the user can select an image file and then click submit. This works but the url of the current page changes to localhost:1337/ad/upload. I want the page to stay at the same url.
$("form#uploadForm").submit(function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
var posting = $.post(url, formData);
})
I have tried this to send the form using jquery but i get an error : Uncaught Type error : Illegal Invocation
What data does the form submit when the type is multipart /formdata and how can we get this data on jQuery
Upvotes: 9
Views: 36661
Reputation: 5855
For those looking for a more modern approach, you can use the JS Fetch (without additional lib - jquery).
var formData = new FormData(this);
fetch(url, {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
//success
} else {
throw Error('Server error');
}
})
.catch(error => {
console.log('fail', error);
});
Upvotes: 0
Reputation: 334
processData
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
Please check jQuery Ajax Documentation
Try ajax like this -
var form = new FormData($("#uploadForm")[0]);
$.ajax({
url: your_url,
method: "POST",
dataType: 'json',
data: form,
processData: false,
contentType: false,
success: function(result){},
error: function(er){}
});
Upvotes: 28
Reputation: 5246
You can give to the formData all form for processing
var form = $('#uploadForm')[0];
// You need to use standart javascript object here
var formData = new FormData(form);
or specify exact data for formdata
var formData = new FormData();
formData.append('userPhoto', $('input[type=file]')[0].files[0]);
Upvotes: 1