javascript - Trying to send input file data over AJAX, can't access the data in my controller -
i'm using laravel 3, , ajaxing in user comment. adding images comment , can't seem file data go through. when set processdata false, unable access other data such comment , privacy. insight?
var commentforms = $('form.compose'); commentforms.on('submit', function(e){ e.preventdefault(); var file = document.getelementbyid('file_input').files[0]; $.ajax({ type: 'post', url: '/issue/comment/' + issue_id, processdata: false, data: { side: side, comment: comment, privacy: privacy, file: file, }, success: function(response){ console.log(response); new_comment = comment_template(response); updateside(new_comment); }, });
going off of kevin b commented, there couple ways this.
first, reason not working that, default, cannot send files ajax request. it, , why isn't working. no matter form , ajax request, stuck. (ajax here meaning not xmlhttprequest2)
solution 1
kevin b recommended javascript formdata object part of xmlhttprequest level 2. information on how use can found: https://developer.mozilla.org/en-us/docs/web/guide/using_formdata_objects in relation code, code along lines of:
commentforms.on('submit', function(e){ e.preventdefault(); var odata = new formdata(document.forms.nameditem("composeform")); var oreq = new xmlhttprequest(); oreq.open("post", '/issue/comment/' + issue_id, true); //on side note, issue_id isn't declared anywhere... oreq.onload = function(oevent) { if (oreq.status == 200) { console.log("uploaded!"); } else { console.log("error " + oreq.status + " occurred uploading file."); } }; oreq.send(odata); }); problem
again, kevin b said, isn't supported. checking here: http://caniuse.com/xhr2 can see ie9 , below isn't supported, xp, vista, , non-upgraded windows 7. if app on own controlled network, , can ensure using firefox/chrome/ie10+, go. if going using feature public, need solution.
other solutions
many sites use ajax upload files, or trick thinking ajax. other websites 1 of 2 things: hidden iframes or flash.
the hidden iframe trick create iframe populates data of current form, , sends off would, meaning page reload. because in iframe , hidden, user never sees page reload , content uploaded expect.
the flash trick use little flash app/plugin finds file , sends server. easy use, , since flash supported, can trick on browsers. have include plugin , go.
plugins
i prefer use plugins, hard work me. 1 fond of right it's simplicity fine uploader. easy configure, looks great, can bootstrapped, or used jquery. plugins may use 1 or both methods upload files, or may try xmlhttprequest2 first, fall on 1 of other methods upload files. ultimately, of popular plugins easy configure , provide decent documentation want.
other popular plugins:
Comments
Post a Comment