Why won’t my AJAX form upload a file?
Do you ever have those dumb moments? You waste a whole load of time trying to get a piece of code to work and performing the most complex de-bugging on it only to realise that you have overlooked the most basic and obvious thing?
Yesterday I was putting together an image upload script, which I wanted to do with AJAX. I wanted to have a file upload box at the top of the screen, press upload, have a nice spinning graphic whilst it uploaded, and then have the image fade into a gallery below. I tried all the AJAX methods with Mootools, checked and double checked my form enctype, until it dawned on me…
When you submit forms via AJAX, then it runs through Javascript (that’s all AJAX is of course). The Javascript takes the content of the form boxes and then sends it through an AJAX request. What Javascript cannot do is access local files on your machine, which is why a file upload field on an AJAX form will not work.
D’oh! I couldn’t believe I’d been so stupid. I put it down to the excessive hours I’ve been working…
Anyway, how about a simple workaround?
Put an IFRAME on the page with invisible borders and load up a file in that. Works perfectly, and although the page in the frame is reloading, it doesn’t appear to be at all. End result is exactly what I wanted and very simple.