I’m trying to create a simple file upload form for my website. I’m using a hidden iFrame to do it “ajax” style so I can have a user upload files one after another using the same form.
Right now I have a form with an <input type="file" />. What I have happening is when the input field changes(user selects a file) it should submit the form with the target set to the iFrame which loads a php script and then reset the input field to allow the user to upload again. What seems to happen is the form gets submitted based on the amount of times the form was submitted. e.g if you press the button when the page loads it will submit one time, however if you press the button again(without reloading the page) it will submit two times, and when you press the button for a third time it will submit the form three times and so on.
Here is my javascript for when the input changes
newupload is the id of the input
newimgform is the id of the form
postframe is the id of the iframe
$("#newupload").change(function() {
var max = 5242880, iframe = $("#postframe"), iframeContents;
$('#newimgform').attr("action", "uploadPicture.php")
$('#newimgform').attr("method", "post")
$('#newimgform').attr("MAX_FILE_SIZE", max)
$('#newimgform').attr("enctype", "multipart/form-data")
$('#newimgform').attr("encoding", "multipart/form-data")
$('#newimgform').attr("target", "postframe")
$('#newimgform').submit();
$("#postframe").load(function() {
iframeContents = jQuery.parseJSON($(this.contentDocument).find('body').html());
alert(iframeContents.filename);
$("#newimgform")[0].reset();
});
});
I looked for anyone else trying this and I’ve seen some answers on here that talk about the submit is being bound multiple times and I need to use unbind like $('#newimgform').unbind("submit").submit(); but that doesn’t seem to do anything. I can’t use any flash uploaders or anything so this has to be pure html/javascript/php.
You can move out the iframe load handler because it need not be added every time you upload a file. And also you can optimize your code like this.