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):
<form id ="send_message_form" target="multipart_uploader_iframe"
method="post" enctype="multipart/form-data" action="/upload_file">
<input type="file" name="upload_image" />
<input type="submit" value="Submit" />
</form>
2. I created iframe
when submit clicked (I tried to avoid unnecessary onload
event firing). Notice, after adding iframe
to body, I added attribute onload
. Because if I add onload attribute while creating iframe, it instantly fired when I append iframe
to body
. Now closePopup
is called once when server responded.
$('#send_message_form').submit(function() {
var customIframe = $('<iframe></iframe>');
customIframe.attr({
'id': "multipart_uploader_iframe",
'name': "multipart_uploader_iframe"
});
$('body').append(customIframe);
customIframe.attr({
'onload': "closePopup();"
});
return true;
});
3. When server responds with responseText (if it returns with text/plain type), responseText will be put in iframe
body. Then iframe
's onload event fires (of course our closePopup function). In my case server responded with OK or other error text:
// Generated by CoffeeScript
window.closePopup = function() {
var error, response, _ref, _ref1;
setTimeout(function() {
return $('#multipart_uploader_iframe').remove();
}, 500);
try {
response = (_ref = (_ref1 = frames['multipart_uploader_iframe']) != null ?
_ref1.document.getElementsByTagName("body")[0].innerHTML : void 0) != null ? _ref : "";
if (response.indexOf("OK") !== -1) {
// close here your popup or do something after successful response
alert('Message has been sent successfully.');
return $(".popup").dialog('close');
}
} catch (_error) {
error = _error;
throw new Error(error);
}
return alert("Error occurred while sending message.");
};
I'm really inspired by this article. I hope this helps someone who has the same problem.
PS: It worked on IE8