I haven’t used much javascript before, and I’m not much of a php programmer either, come to think of it, but I’m attempting to learn by building a little website.
I’ve got a form which has a file upload input which I’m attempting to make all nice sexy with this great script but there doesn’t appear to be a tutorial and the code isn’t commented.
(I think) I know how to make it work ok but I’m interested in how it works. Does anyone fancy taking a quick look at it and telling me what all the code in the js and php file is doing?
I’d really appreciate it 🙂
I wouldn’t recommend using this library, first of all, since there are much better ones out there, but your question was how this one worked, not whether it was a good one or not.
Here goes:
ajaxUploadis called by one of the buttons in the upload form.ajaxUploadfirst ensures that all the function arguments are correct, creating an alert box (!) if there’s a problem with one of them. (It would be a better idea to throw an error usingthrow "error message"instead.)ajaxUploadthen creates an iframe usingdocument.createElement, and gives it zero width and height so it’ll be invisible, before adding it to the document. It gives the iframe the nameajax-temp.ajaxUploadadds thedoUploadfunction as aonloadlistener on the iframe. It uses theaddEventfunction as a cross-browser way to do this.ajaxUploadsets the calling form’stargetattribute to point to the iframe, using the name that it gave the iframe earlier. This causes the form to submit into the iframe, instead of replacing the current page. The function also sets some other attributes on the form, even though it would probably be a better idea to add those attributes in the HTML source and not from Javascript.ajaxUploadsubmits the form usingform.submit().ajaxupload.phpto run.ajaxupload.php, the script first checks that the browser did actually send a file (in case a curious user visited the url manually instead of submitting the form), then calls theuploadImagefunction with a bunch of parameters that it got from the$_REQUESTobject.uploadImagedoes a bunch of checks on the arguments it receives from the client, making sure that the file isn’t too big, has the right extension, etc. If all the checks are passed, it saves the image and returns the filename where the image was saved. Otherwise it returns the list of errors.uploadImageisn’t an array of errors, the script returns a success message and an<img>tag with it’ssrcset to the url of the image. Otherwise, it returns a failure message.loadevent on the iframe to fire. ThedoUploadfunction, which is registered as a listener, is called.doUploadremoves itself as a listener from the iframe, and runs some javascript code in the context of the iframe by setting the iframe’s src attribute. This code copies the iframe’s contents to the parent page.doUploadremoves the iframe from the document, waiting a short time beforehand in some browsers.Whew, that sure took a while to write.