ie javascript form submit with file input - javascript

I have a html form, with a custom file upload field. And by that I mean that I have moved the actual file field beyond the borders of the page with css, that I have a custom input field and button in place, and that I have a jquery click event attached to that custom button to trigger the file input dialog.
It all works fine, in every browser.
But I need to submit the form through javascript. And I got somewhere that IE remembers my actions with javascript as a malicious manipulation of the file input field and blocks my access with an error "access denied" when I invoke document.formName.submit().
Is there a way around this, because I have gone completely mad by trying to search for a solution. I seriously don't want to use the default file input field, as every browsers renders it differently and messes up my design..
code:
<form name="thisForm" onsubmit="return false;" enctype="multipart/form-data" method="post" action="index.cfm/somepage">
<input type="file" class="hidden" name="hidden" id="hidden" />
<input type="text" name="shown" id="shown" />
<button id="button">browse..</button>
<input type="submit" id="submitForm" />
</form>
<script>
$('button').click(function(){
$('#shown').val($('#hidden').val());
});
$('submitForm').click(function(){
validateForm();
});
function validateForm()
{
//regular expression validation against all other input fields in the form
//not the file input field
validateVAT();
}
function validateVAT()
{
//connect to external service to check VAT
submitForm();
}
function submitForm()
{
document.thisForm.submit();
}
</script>
UPDATE:
I just tried to first upload the file, before submitting the form, through ajax, but that also gave me the acces denied error.. >_>

I was having the same problem, and I solved it by using a styled <label> tag with a slight workaround in Firefox.
http://jsfiddle.net/djibouti33/uP7A9/
The Goals:
allow user to upload a file by using standard html file input control
hide standard html file input control and apply own styling
after user selects file to upload, automatically submit the form
The Browsers:
Firefox, Chrome, IE8/9, Safari
IE7 didn't work, but it might if you add it to the workaround detailed below.
The Initial Solution:
Hide the file input by positioning it offscreen. Important not to display:none as some browsers won't like this.
Add another styled element to the page (link, button).
Listen for a click on that element, then programmatically send a click to the file input to trigger the native 'file explorer'
Listen for the file input's onchange event (occurs after a user chooses their file)
Submit the form
The Problem:
IE: if you programmatically send a click to a file input in order to activate it (2), programmatically submitting the form (5) will throw a security error
The Workaround Solution:
Same as above
Take advantage of the accessibility features built in to the label tag (clicking on a label will activate it's associated control) by styling
a label tag instead of a link/button
Listen for the file input's onchange event
Submit the form
For some reason Mozilla browsers won't activate a file input by clicking on it's label.
For Mozilla, listen for the click on the label and send a click event to the file input to activate it.
Hope this helps! Check out the jsfiddle for details on the html/js/css used to make it all work.

I found the answer myself, After 2 days of crazy trial&error. I hope I can help somebody with this..
I removed the hidden file input field from my coldfusion page and replaced it by an iframe tag. That iframe tag linked to another coldfusion page, containing another form with the removed file input field.
Now when I use javascript to click the file input field, which is still hidden from view, it still gives the browse file dialog without a hitch. But when I use javascript to submit the form, through the iframe, miraculously, it submits the form in the iframe, making it possible to upload the file in some serverside scripting of your preference.
iframe code:
<form id="formFileUpload" class="formFileUpload" name="formFileUpload" method="post" action="../actions/act_upload_file.cfm" autocomplete="off" enctype="multipart/form-data">
<input type="file" class="buttonFileHidden" id="inputFile" name="partnersLogo" />
</form>
iframe itself:
<iframe src="admin/dsp_file_upload.cfm" id="ifu" name="ifu" class="buttonFileHidden">
</iframe>
javascript click & submit:
ifu.document.formFileUpload.partnersLogo.click();
ifu.document.formFileUpload.submit();

If you're like me, and you don't want to use an iframe, and you weren't too keen on the label solution mentioned above, you can just position the original button above the styled button with an opacity of 0.
Using the example above, you would still have:
<input type="file" class="hidden" name="hidden" id="hidden" />
<input type="button" name="shown" id="shown" value="Add File" />
But .hidden would be defined like so:
.hidden {
position: absolute;
left: -150px;
opacity: 0;
filter: alpha(opacity=0);
}
Config: Set the opacity to 0.5 (or =50) to see the transparent element and tweak the left positioning.
Arguably just as hacky as the answers above, but a bootstrap-friendly solution, and in my case, the only one that worked.

I found a weird solution to solve this problem.
It thought about the js click thread. If it goes out of this thread, there no more security issues.
I chose to use window.setTimeout. see sample below:
<script type="text/javascript">
$(function () {
$("#<%= this.fuDoc.ClientID %>").bind('change', uploadFile);
$("#<%= this.btnUpload.ClientID %>").click(chooseFile);
});
function chooseFile() {
$("#<%= this.fuDoc.ClientID %>").click();
}
function uploadFile() {
var fu = $("#<%= this.fuDoc.ClientID %>");
if (fu.val() != "") {
window.setTimeout(function () {
<%= this.ClientScript.GetPostBackEventReference(this.btnUpload, "") %>;
}, 100);
}
}
</script>
<asp:FileUpload ID="fuDoc" runat="server" style="display: none;" />
<asp:Button runat="server" ID="btnUpload" Text="upload" OnClick="btnUpload_Click" />
<asp:Label ID="lbltext" Text="" runat="server" />`
then, no more acces denied!

This is an old post but the problem still arises. This may not be working because jQuery kindly fails silently. I was having this problem and wondering why my hidden form would not submit and the file get uploaded. I started off by using jQuery, but then I went vanilla. It still didn't work but looked as though an exception was being thrown in my .click() function.
Running
try {
document.getElementById('formid').submit();
} catch (e) {
alert(e);
}
showed that we indeed were throwing an error, and quick research showed that this was because IE DOES NOT SUPPORT SIMULATED CLICKS ON A FILE INPUT. This means that when the form went to be posted, IE would refuse to post the form
Excuse the bold caps, but I know many people will see text and not read it

Have you tried
$('button').click(function(){
$('form[name=thisForm]').submit()
});

You need to change onsumbit='return false;' to onsubmit='return validateForm()'.
Then have validateForm() return true if the form passes your validation checks, or false if it does not.
The onsubmit='return false' is preventing the form from submitting via document.thisForm.submit(); as well as when the user clicks the submit button.

I commented these lines in j query.form.js then every thing works fine for me. Don't ask me the reason even i don't have the solution for that but it works for sure.
if (io.contentWindow.document.execCommand) {
try { // #214
io.contentWindow.document.execCommand('Stop');
} catch(ignore) {}
}

Related

HTML input "disabled" attribute not working in Bootstrap modals

I have a webpage with an "edit" form that appears in a modal dialog using Bootstrap.
When the form appears, I would like one of the input fields to be disabled at first, and to be enabled if the user clicks a checkbox.
The problem is, my browser (Chrome) is not reflecting the disabled attribute for any form element within the modal dialog. Any form element outside the modal works fine.
This also works fine on another webpage I have with the exact same logic. It is only misbehaving on this page.
I have run the entire page source through the W3 Validator for HTML5 and get no errors back.
Code for the input element:
<form role="form" id="frmEdit" action="group_edit.php" method="post">
<!-- ... -->
<input type="text" id="txtEditAlternate" class="form-control" name="alternate" disabled />
<!-- ... -->
</form>
I even tried to brute force disable it with jQuery on document ready; this does not work:
$(document).ready(function() {
$("#txtEditAlternate").attr("disabled", true);
// ...
});
The only thing that does work when it comes to disabling the text field is when the checkbox is checked and then unchecked:
$("#chkbox").click(function() {
$("#txtEditAlternate").attr("disabled", !$(this).prop("checked"));
});
Although that kind of defeats the purpose, since the text field is supposed to be disabled until the checkbox is checked.
I have read that simply including disabled with no value is valid HTML5 (the validator did not even warn about this), and it works elsewhere.
I have tried everything I can think of, and can only speculate that it has something to do with the Bootstrap modal functionality. But like I said, the same logic works perfectly on another webpage I have.
And yes, I know Chrome likes to cache things. I have "hard-refreshed" many times, does not change anything.
Any suggestions?
try to use disabled="disabled":
<input type="text" id="txtEditAlternate" class="form-control" name="alternate" disabled="disabled" />
Use readonly attribute instead of disabled.
use prop instead of attr
$("#txtEditAlternate").prop("disabled", true);

Ajax form submit with input type file

I am using ajax to submit a form that browses, uploads and then processes a file using PHP. I hate the standard html input type="file" button (as most people do) so used a trick to click the standard "browse" button from another button (id="fileSelect") that I can eventually customize. Works great in safari and others, but with IE the ajax code line that submits the form does not fire. Other elements of the ajax code are executed (I get the alert("Ajax complete"); at the end), but the "$("#imageform").ajaxForm({target: '#preview'}).submit();" line does not work in IE.
Ajax code:
$(document).ready(function()
{
$('#xfile').live('change', function() // when there is an even on the 'file' element (like file selected)
{
$("#preview").html(''); // clears the preview area
$("#preview").html('<img src="general_images/loading.gif" alt="Uploading...."/>'); // displays the loading
$("#imageform").ajaxForm({target: '#preview'}).submit();
alert ("Ajax complete");
});
});
And HTML Code:
<div>
<button id="fileSelect" onclick="document.getElementById('xfile').click();">Insert Picture</button>
<form style="display: inline" id="imageform" name="imageform" action="upload_file_journal.php" method="post" target="_blank" enctype="multipart/form-data">
<input style="visibility: hidden" type='file' name='xfile' id='xfile' /
</form>
This will not work in IE 9 and older(I think it works in IE 10,11).
The only real option is to use absolute positions to place your upload control on top of your button, then set the opacity to 0.1, then they look like they are clicking a button, but are actually clicking the input, you have to super size the file input to ensure they always click the button part.
Even doing that is a hassle though.
Hope this helps

IE clears input[type="file"] on submit

I have a page (demo):
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function() {
$("#id_button").click(function(e) {
$("#id_file").click();
});
});
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="http://www.google.com/">
<input type="file" name="file" id="id_file" />
<input type="button" id="id_button" value="fake button" />
<input type="submit">
</form>
</body>
</html>
if
I open browse dialog via clicking "fake button", select file (I see it in input[type="file"]), than click submit button and no post happens, the input[type="file"] is cleared.
What should I changed to get it work?
I get this problem in IE8 and IE10.
PS: file input will be hidden, so user will work only with fake button.
All of the browsers have different behavior when it comes to what they allow you to do from javascript with regards to programmatically clicking the input button for file inputs.
The best solution I have found that seems to work cross browser is to set the opacity to 0 (do not use display:none) and put the button underneath the input, so the user clicks through the 0 opacity input to your button, thus firing the input select dialog.
A good writeup on styling the file input can be found here: http://www.quirksmode.org/dom/inputfile.html
http://jsfiddle.net/j38Wj Works fine in Google Chrome but does not work in IE 10.
As I think IE does not allow select file by external 'click' event.
Only one way to "customize" input[type=file] is usage of opacity style to hide it and relative positioning of custom button control below it.
Working example: http://blueimp.github.io/jQuery-File-Upload/
[...]
I think all browser does that behaviour for security reason. When you submit a form, you are redirected to a different page(or the same page) and if you are directed to the same page, the form is re-initialized.
In this case, you simply can NOT set the value of file for security reason.
From example, How to set a value to a file input in HTML?, you don't want this happen
<form name="foo" method="post" enctype="multipart/form-data">
<input type="file" value="c:\passwords.txt">
</form>
<script>document.foo.submit();</script>
Add a label tag along with the input file element. Set the 'for' attribute of the label to the id of the input file element.
Then when you click on the label the input file element will 'click' and the file dialog will open.
Then simply style the label however you like. Have tried on various IE versions.

Triggering a input file click does not bring the file upload dialog

I have the following HTML:
<form method="post" action="/link" style="position:absolute; left:-1000px;">
<input type="file" name="gameUpload" id="gameUpload" />
</form>
I am trying to integrate the upload feature in HTML into unity.
The idea is when a button is clicked in unity engine, it will make a call to a javascript function and the js function will trigger the click on the file input element.
This works perfectly fine in Firefox and IE10, IE9 and IE8. But it is not working in Chrome and Safari.
The JS code:
function uploadImage(){
jQuery("#gameUpload").trigger("click");
}
I tried having a "span" with some text and tried triggering the file input's click when that text is clicked, that worked fine.
Also, I did the following to check whether the click is triggered:
jQuery("#gameUpload").unbind("click").bind("click",function(){
alert("I am open");
});
Apparently, the click is getting triggered because I am getting the alert but the file dialog is not getting opened.
I'm not familiar with HTML in Unity, but I don't think you need the JS.
Just including the <input type="file" name="gameUpload" id="gameUpload" /> should allow the browser to open a dialog window.
With jQuery, just do this:
$('#imageUpload').click();
// or get the HTMLElement
$('#imageUpload').get(0).click();
Use html only (as we know, label with for attribute will focus the form element's default actions so.)
<label for="imageUpload">Upload File!</label>
<input id="imageUpload" type="file" style="display:none"/>

Getting inputs to auto-complete/suggest when preventing default form behavior

Interesting bug here that seems to be limited to IE and Webkit.
I have a basic form setup:
<div id="output">Form output is displayed here</div>
<form id="myForm" action="#" method="post">
<input type="text" name="username" id="usernameInput" />
<input type="submit" value="Submit" />
</form>
Now if I just submit the form through a normal page refresh, the next time I go to type text into the input field, I will get the browser's default auto-suggest dropdown (this is the intended behavior). However, if I highjack the form submission behavior in order to do an AJAX submit:
$('#myForm').submit(function () {
$('#output').text($('usernameInput').val());
return false;
});
Now when I submit the form, the output div updates, but the previous values that I input into the form aren't stored and no suggestions will be made when you type.
Does anyone have any creative solutions to this problem? Maybe an (gulp) iframe?
IE and WebKit only remember values that were submitted normally, and since you are submitting it through AJAX, those engines do not remember the values. Instead of an iframe, I would use a jQuery plugin for the autocomplete, like this one. Of course, with that solution, you will need to maintain a listing of what a user has typed in the past, which shouldn't be too hard.
test with these modifications in controlling submit:
$('#myForm').submit(function (e) {
e.stopPropagation();
$('#output').html($("#usernameInput").val() + "<br />");
});

Categories

Resources