php - Use jQuery AJAX to upload a file via FormData -
i want upload single file using jquery , replace upload form output php script has processed file upload.
currently after click submit, receive blank response php script. think it's because form data (file , upload inputs) being overwritten upload data?
any solving appreciated!
here code:
html
<div id="container"> <form id="form" enctype="multipart/form-data"> <input name="file" type="file"> <input type="hidden" name="upload"> </form> <a href="javascript:void(0)" onclick="uploaddata($('#form').serialize(), 'upload.php', '#container'); return false;">upload ></a> </div>
javascript
function uploaddata(data, url, container) { var formdata = new formdata($(data)[0]); $.ajax({ type: 'post', url: url, data: formdata, cache: false, contenttype: false, processdata: false, success: function(response) { $(container).html(response); }, error: function() { alert('error!'); }, }); return false; };
php
if (isset($_post['upload'])) { // check file has been uploaded if (isset($_files['file'])) { // check if there error uploading file if ($_files['file']['error'] > 0) { // display error echo 'error: ' . $_files['file']['error']; } else { // move , store file (overwrite if exists) $filename = '/upload/' . $_files['file']['name']; move_uploaded_file($_files['file']['tmp_name'], $filename); echo 'file uploaded successfully'; } } else { die ('error: no file selected upload'); } }
i don't think ajax can handle file uploads. have checked file uploaded?
if true, response empty because isset($_post['upload'])
returns false
. try adding last else statement, check i'm saying:
if (isset($_post['upload'])) { ... } else { die ('error: ajax cannot handle file uploads'); }
Comments
Post a Comment