JQuery - FormData Objekt (AJAX): Unterschied zwischen den Versionen
Aus Wikizone
(Die Seite wurde neu angelegt: „For correct form data usage you need to do 2 steps. Preparations You can give your whole form to FormData() for processing <syntaxhighlight lang="javascript"…“) |
|||
| Zeile 1: | Zeile 1: | ||
| + | https://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload | ||
For correct form data usage you need to do 2 steps. | For correct form data usage you need to do 2 steps. | ||
Aktuelle Version vom 11. Februar 2019, 13:55 Uhr
https://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload
For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
After this it will send ajax request like you submit regular form with enctype="multipart/form-data"
Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.
Note: contentType: false only available from jQuery 1.6 onwards