javascript - How to use FormData for ajax file upload -
this html i'm generating dynamically using drag , drop functionality.
<form method="post" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data"> <fieldset> <div id="legend" class=""> <legend class="">file demoe 1</legend> <div id="alert-message" class="alert hidden"></div> </div> <div class="control-group"> <!-- text input--> <label class="control-label" for="input01">text input</label> <div class="controls"> <input type="text" placeholder="placeholder" class="input-xlarge" name="name"> <p class="help-block" style="display:none;">text_input</p> </div> <div class="control-group"> </div> <label class="control-label">file button</label> <!-- file upload --> <div class="controls"> <input class="input-file" id="fileinput" type="file" name="file"> </div> </div> <div class="control-group"> <!-- button --> <div class="controls"> <button class="btn btn-success">button</button> </div> </div> </fieldset> </form>
this js code...
<script> $('.wpc_contact').submit(function(event){ var formname = $('.wpc_contact').attr('name'); var form = $('.wpc_contact').serialize(); var formdata = new formdata($(form)[1]); $.ajax({ url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php', data : {form:form,formname:formname,ipadd:ipadd,formdata:formdata}, type : 'post', processdata: false, contenttype: false, success : function(data){ alert(data); } }); }
for correct form data usage need 2 steps.
preparations
you can give whole form formdata() processing
var form = $('form')[0]; // need use standard javascript object here var formdata = new formdata(form);
or specify exact data 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 jquery looks this:
$.ajax({ url: 'your url here', data: formdata, type: 'post', contenttype: false, // needed, don't omit (requires jquery 1.6+) processdata: false, // needed, don't omit // ... other options success , etc });
after send ajax request submit regular form enctype="multipart/form-data"
update: request cannot work without type:"post"
in options, cause files must sent via post request.
note: contenttype: false
available from jquery 1.6 onwards
Comments
Post a Comment