Is there any chance to handle when form submit finished(ok or error)? I want to upload images or mulitpart data without javascript libraries. For example, user clicks submit
button, after uploading data server responds with error
or success
response. Depending on that result I need to do something. Here is example form:
<form method="post" enctype="multipart/form-data" action="/upload_file">
<input type="file" name="upload_image" />
<input type="submit" value="Submit" />
</form>
One non-ajax option is to have a hidden
iframe
on the page with a name, and to set thetarget
action of your form to the name of thatiframe
. Have the server respond with a cookie that's specific to the form (you might even pass in anid
the server should use as the cookie name), then on form submit start polling to see if that cookie exists. When the cookie arrives, it means the server has replied to the form post in theiframe
. You can either put the success/failure information in the cookie itself, or put it in the document that ends up in theiframe
and have your client-side code scrape it from there. Then take appropriate action.E.g., in pseudo-code:
I first came up with this technique to answer this other question here, immediately used it on a project, and it works a treat. In the case of that question, we were dealing with something that would return a document to download (
Content-Disposition: attachment
) (I used it to show a "Building your document"div
and then replace that with success/failure when the cookie arrived), but it works perfectly well if you're doing something else.Since I've not access to the server side, I need to solve this problem on the client side. That's why I couldn't use cookies.
I did these steps to achieve success (I used jQuery to create/bind element/events. I didn't use AJAX to send form data):
1. I have iframe in my HTML (pay attention, there is no
iframe
in HTML):2. I created
iframe
when submit clicked (I tried to avoid unnecessaryonload
event firing). Notice, after addingiframe
to body, I added attributeonload
. Because if I add onload attribute while creating iframe, it instantly fired when I appendiframe
tobody
. NowclosePopup
is called once when server responded.3. When server responds with responseText (if it returns with text/plain type), responseText will be put in
iframe
body. Theniframe
's onload event fires (of course our closePopup function). In my case server responded with OK or other error text:I'm really inspired by this article. I hope this helps someone who has the same problem.
PS: It worked on IE8