yBrowser: IE9
Technologies: MVC5
I am mainly using Angular for everything on my page. (Single Page App).
But because I am working with IE9, I can't use FileAPI.. So, I decided to go with MVC's Form Actions to get HttpPostedFileBase in my controller methods to handle fileupload.
Html Code: (Is present in a modal)
#using (Html.BeginForm("UploadTempFileToServer", "Attachment", FormMethod.Post, new { enctype = "multipart/form-data", id = "attachmentForm" }))
{
<div>
<span id="addFiles" class="btn btn-success fileinput-button" ng-class="{disabled: disabled}" onclick="$('#fileUpload').click();">
<span>Add files...</span>
</span>
<input id="fileUpload" type="file" name="files" class="fileInput" onchange="angular.element(this).scope().fileAdded(this)" />
</div>
<div>
<span class="control-label bold">{{currentFilePath}}</span>
<input name="fileUniqueName" value="{{fileUniqueName}}" />
<input id="attachmentSubmit" type="submit" value="Upload File" />
</div>
}
MVC Controller:
public void UploadTempFileToServer(IEnumerable<HttpPostedFileBase> files, string fileUniqueName)
{
var folderPath = fileStorageFolder;
foreach (var file in files)
{
if (file.ContentLength > 0)
{
file.SaveAs(folderPath + fileUniqueName);
}
}
}
Question #1: Does anyone know of a way to send the HttpPostedFileBase data to the controller, without using form's submit action?
I don't mind using Jquery if need be. I have tried hijacking the form's submit action and that didn't work.
I tried sending the file control's data using non submit button event, but no luck there either.
If not:
Question #2 How do I prevent the page from going to /Attachment/UploadTempFileToServer after the execution of submit is completed?
To answer #2 (and assuming you're using jQuery):
$(document).on('submit', '#attachmentForm', function(event){
event.preventDefault();
// everything else you want to do on submit
});
For #1, unfortunately, unless a browser supports XMLHttpRequest2 objects (which I don't believe IE9 does), you can't send file data via ajax. There are plugins that let you submit the form to a hidden iframe, though. I think Mike Alsup's Form plugin has that ability: http://malsup.com/jquery/form/#file-upload
So, after much research and attempts. This is my solution:
Using https://github.com/blueimp/jQuery-File-Upload/wiki
HTML:
Earlier I was using a hidden file upload control and triggering its click via a span. But because of security issues a file input which is opened by javascript can't be submitted by javascript too.
<div class="col-md-7">
<div class="fileupload-buttonbar">
<label class="upload-button">
<span class="btn btn-success btnHover">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<input id="fileUpload" type="file" name="files"/>
</span>
</label>
</div>
</div>
Javascript:
$('#fileUpload').fileupload({
autoUpload: true,
url: '/Attachment/UploadTempFileToServer/',
dataType: 'json',
add: function (e, data) {
var fileName = data.files[0].name;
var ext = fileName.substr(fileName.lastIndexOf('.'), fileName.length);
var attachment = {
AttachmentName: fileName,
Extension: ext
}
var fileUniqueName = id + ext;
//Sending the custom attribute to C#
data.formData = {
fileUniqueName: fileUniqueName
}
data.submit().success(function (submitData, jqXhr) {
attachment.Path = submitData.path;
//Add the attachment to the list of attached files to show in the table.
$scope.attachmentControl.files.push(attachment);
//Since this is not a direct angular event.. Apply needs to be called for this to be bound to the view.
$scope.$apply();
}).error(function (errorData, textStatus, errorThrown) {
});
},
fail: function (data, textStatus, errorThrown) {
}
});
C#:
public virtual ActionResult UploadTempFileToServer(string fileUniqueName)
{
//Getting these values from the web.config.
var folderPath = fileStorageServer + fileStorageFolder + "\\" + tempFileFolder + "\\";
var httpPostedFileBase = this.Request.Files[0];
if (httpPostedFileBase != null)
{
httpPostedFileBase.SaveAs(folderPath + fileUniqueName);
}
return Json(new
{
path = folderPath + fileUniqueName
},
"text/html"
);
}
Related
I have an issue where my checkbox list is not binding when loading data from the server.
So I have a table where you select a client when I click the edit button a bootstrap modal window popup with all the information fields such as first name, last name etc.
Now a couple of these fields are checkbox lists. Everything is being populated with the correct data except these two fields. Below is the current code of one of the lists.
<div class="row">
<div class="col-25">
<label for="referralSource">Referral Source</label>
</div>
<div class="col-75">
<ul class="kolist" data-bind="foreach: $root.sources">
<li>
<input type="checkbox" data-bind="
checkedValue: id,
checked: $root.currentClient.ReferralSourceIDs
" />
<label style="margin: 0px; padding: 0px;" data-bind="
text: source,
attr: {for: source}
"></label>
</li>
</ul>
</div>
</div>
This code should bind the data from the currentClient which is in the viewmodel.
self.currentClient = ko.observable();
On the edit button being clicked the currentClient is filled with the correct data.
editClient = function (editingClient) {
self.currentClient(editingClient);
}
The data we receive from the database fills up the ReferralSource class.
function ReferralSource(id, source) {
this.id = ko.observable(id);
this.source = ko.observable(source);
return this;
}
clientsLoad = function () {
$.ajax({
contentType: 'application/json',
type: "GET",
url: baseUrl + 'api/Client/LoadAll',
dataType: 'json',
context: this,
success: function (data, textStatus, jqXHR) {
self.clients($.map(data, function (item) {
var referralSources = new Array();
for (var i = 0; i < item.ReferralSourceIDs.length; i++) {
referralSources.push(
new ReferralSource(
item.ReferralSourceIDs[i].ReferralSourceID,
item.ReferralSourceIDs[i].Source
)
);
}
return new Client(
item.FirstName,
item.LastName, /* etc */
referralSources
);
}));
}
});
}
So with all that being said the load data is working fine the edit on select is being populated with the correct data but the only issue is that the check boxes are not being selected on bind. Can anyone see something I am missing or am I doing something wrong. If you need more info please ask, I will be trying to get this to work in the meantime.
EDIT: So I found a way to get it working and it has to deal with this part of the code.
<input type="checkbox" data-bind="checkedValue: id, checked: $root.currentClient.ReferralSourceIDs" />
It does not like $root.currentClient.ReferralSourceIDs. I removed this out of the class and put it into the view model and it started to work. So it looks like this now $root.referralSources. I have no idea why but it works that way. So if anyone has any other solutions please let me know for now I will stick with this.
I am trying to attach some files (zero/single/multiple) and send them as attachments to an email using ANGULARJS and spring.
One thing noticed is when selecting the files from multiple directories only the recently selected file is shown and previous selected file is not shown. How can I show all the files selected by the user from different directories too and give the ability to delete the file (all files or one file) before submitting the form.
Demo:http://plnkr.co/edit/M3f0TxHNozRxFEnrqyiF?p=preview
html:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
TO: <input type="text" name="to" id="to" ng-model="to" required ></input><br>
Subject : <input type="text" name="subject" id="subject" ng-model="subject"></input>
<br>Attachment: <input type="file" ng-file-model="files" multiple /> <br>
<p ng-repeat="file in files">
{{file.name}}
</p>
<textarea rows="20" maxlength=35000 name="message" ng-model="message" ></textarea>
<button type="button" ng-click="upload()">Send</button>
</body>
js:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.files = [];
$scope.upload=function(){
alert($scope.files.length+" files selected ... Write your Code to send the mail");
};
});
app.directive('ngFileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.ngFileModel);
var isMultiple = attrs.multiple;
var modelSetter = model.assign;
element.bind('change', function () {
var values = [];
angular.forEach(element[0].files, function (item) {
var value = {
// File Name
name: item.name,
//File Size
size: item.size,
//File URL to view
url: URL.createObjectURL(item),
// File Input Value
_file: item
};
values.push(value);
});
scope.$apply(function () {
if (isMultiple) {
modelSetter(scope, values);
} else {
modelSetter(scope, values[0]);
}
});
});
}
};
}]);
The default browser behavior is showing currently selected files, to cahnge that you've to customize that filed. And also, I saw your custom directive code, it doesn't allow to select multiple files from different directories.
So, what you can do is, create another scope variable & every time user selects file/files you push those files to this array. In this way you've have set of all selected files from same/different directories and then you can have delete functionality over each file which's ultimately going to be updated.
Updated html view part:
Attachment: <input type="file" ng-file-model="files" multiple /><br>
<p ng-repeat="file in filesToUpload track by $index">
{{file.name}} <span class="delete-file" ng-click="deleteFile($index)">X</span>
</p>
And for this new array update directive scope.$apply part as:
scope.$apply(function () {
if (isMultiple) {
modelSetter(scope, values);
} else {
modelSetter(scope, values[0]);
}
if(values){
scope.filesToUpload = scope.filesToUpload.concat(values);
}
});
In controller have deleteFile function as:
$scope.deleteFile = function(index){
$scope.filesToUpload.splice(index, 1);
};
Working Demo Example
Now user'll be able to delete files anytime. But the input field will still show the last selected file/files and after deleting particular file also it'll not change its status so for that you can just hide field by opacity: 0; css & then create customized Upload button & from that trigger click on actual hidden file input element.
Update: Check this update of same code with custom upload button:
Plunker Example
What I want to be abl
e to do is passing the form data to a php file and then having the results passed back into app so that the user isnt directly accessing the php file at any point.
This is what I came up with but I cant get it too pass the data. I used chrome with -disable-web-security. It always returns false so I guess the data isnt being passed to the php file. Any help would be great. Also. when it forwards to the results page, it goes blank after a few seconds. thank you.
HTML
<form id="form" method="POST" data-ajax="false" data-transition="pop" data-direction="reverse">
<fieldset>
<label for="name" class="ui-hidden-accessible">Name</label>
<input type="text" name="name" id="name" value="" class="required" placeholder="Name"/>
<label for="email" class="ui-hidden-accessible">E-Mail</label>
<input type="email" name="email" id="email" value="" class="required" placeholder="E-Mail"/>
<label for="memory" class="ui-hidden-accessible">Memory</label>
<textarea name="memory" name="memory" id="memory" class="required" placeholder="Your Memory..."></textarea>
<label for="submit" class="ui-hidden-accessible">Submit</label>
<input type="submit" name="submit" id="submit" value="SEND">
</fieldset>
</form>
JS
$(document).on('pagebeforeshow', '#formPage', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#name').val().length > 0 && $('#email').val().length > 0 && $('#memory').val().length > 0){
var that = $(this),
contents = that.serialize();
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({
url: 'http://www....',
dataType: 'json',
type: 'post',
data: contents,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function(data) {
console.log(data);
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all nececery fields');
}
return false; // cancel original event to prevent form submitting
});
});
PHP
header('Content-type: text/javascript');
$json = array(
'success' => false,
'result' => 0
);
if(isset($_POST['name'], $_POST['email'], $_POST['memory'])){
$name = $_POST['name'];
$email = $_POST['email'];
$memory = $_POST['memory'];
$json['success'] = true;
$json['result'] = $name;
}
echo json_encode($json);
You are not serializing the form data correctly and the result is that the contents variable is empty.
Change this code:
var that = $(this),
contents = that.serialize();
To this:
//var that = $(this), // <-- delete this line
contents = $('#form').serialize();
YOU ALSO NEED TO FIX ..
You haven't realized it yet but you have created a multiple click binding issue by placing your click handler in the bagebeforeshow event. In order to prevent that from occuring you need to
Change this code:
$(document).on('pagebeforeshow', '#formPage', function(){
To this:
$(document).on('pageinit', '#formPage', function(){
This way your $(document).on('click', '#submit', function() { is only ever bound once regardless of how many times a user leaves and returns to the '#formPage' page
EDITED
No, the data submitted to your backend PHP program via ajax is not json encoded. It is standard HTTP POST data and is accessed via $_POST (or $_REQUEST).
I have your code (with the changes I outlined in my answer above) working on my server. I have placed the two files I setup to test your code in a pastbin for your reference:
The php file:
(edit the path to the included javascript file for your environment)
sandbox_ajax_form.php
The javascript file:
(edit the path that the form data is sent to)
sandbox_ajax_form.js
Can I use a PUT method in an HTML form to send data from the form to a server?
According to the HTML standard, you can not. The only valid values for the method attribute are get and post, corresponding to the GET and POST HTTP methods. <form method="put"> is invalid HTML and will be treated like <form>, i.e. send a GET request.
Instead, many frameworks simply use a POST parameter to tunnel the HTTP method:
<form method="post" ...>
<input type="hidden" name="_method" value="put" />
...
Of course, this requires server-side unwrapping.
XHTML 1.x forms only support GET and POST. GET and POST are the only allowed values for
the "method" attribute.
Can I use "Put" method in html form to send data from HTML Form to server?
Yes you can, but keep in mind that it will not result in a PUT but a GET request. If you use an invalid value for the method attribute of the <form> tag, the browser will use the default value get.
HTML forms (up to HTML version 4 (, 5 Draft) and XHTML 1) only support GET and POST as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly. XHTML 2.0 once planned to support GET, POST, PUT and DELETE for forms, but it's going into XHTML5 of HTML5, which does not plan to support PUT. [update to]
You can alternatively offer a form, but instead of submitting it, create and fire a XMLHttpRequest using the PUT method with JavaScript.
_method hidden field workaround
The following simple technique is used by a few web frameworks:
add a hidden _method parameter to any form that is not GET or POST:
<input type="hidden" name="_method" value="PUT">
This can be done automatically in frameworks through the HTML creation helper method.
fix the actual form method to POST (<form method="post")
processes _method on the server and do exactly as if that method had been sent instead of the actual POST
You can achieve this in:
Rails: form_tag
Laravel: #method("PATCH")
Rationale / history of why it is not possible in pure HTML: https://softwareengineering.stackexchange.com/questions/114156/why-there-are-no-put-and-delete-methods-in-html-forms
for people using laravel
<form method="post" ...>
#csrf
#method('put')
...
</form>
Unfortunately, modern browsers do not provide native support for HTTP PUT requests. To work around this limitation, ensure your HTML form’s method attribute is “post”, then add a method override parameter to your HTML form like this:
<input type="hidden" name="_METHOD" value="PUT"/>
To test your requests you can use "Postman" a google chrome extension
To set methods PUT and DELETE I perform as following:
<form
method="PUT"
action="domain/route/param?query=value"
>
<input type="hidden" name="delete_id" value="1" />
<input type="hidden" name="put_id" value="1" />
<input type="text" name="put_name" value="content_or_not" />
<div>
<button name="update_data">Save changes</button>
<button name="remove_data">Remove</button>
</div>
</form>
<hr>
<form
method="DELETE"
action="domain/route/param?query=value"
>
<input type="hidden" name="delete_id" value="1" />
<input type="text" name="delete_name" value="content_or_not" />
<button name="delete_data">Remove item</button>
</form>
Then JS acts to perform the desired methods:
<script>
var putMethod = ( event ) => {
// Prevent redirection of Form Click
event.preventDefault();
var target = event.target;
while ( target.tagName != "FORM" ) {
target = target.parentElement;
} // While the target is not te FORM tag, it looks for the parent element
// The action attribute provides the request URL
var url = target.getAttribute( "action" );
// Collect Form Data by prefix "put_" on name attribute
var bodyForm = target.querySelectorAll( "[name^=put_]");
var body = {};
bodyForm.forEach( element => {
// I used split to separate prefix from worth name attribute
var nameArray = element.getAttribute( "name" ).split( "_" );
var name = nameArray[ nameArray.length - 1 ];
if ( element.tagName != "TEXTAREA" ) {
var value = element.getAttribute( "value" );
} else {
// if element is textarea, value attribute may return null or undefined
var value = element.innerHTML;
}
// all elements with name="put_*" has value registered in body object
body[ name ] = value;
} );
var xhr = new XMLHttpRequest();
xhr.open( "PUT", url );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = () => {
if ( xhr.status === 200 ) {
// reload() uses cache, reload( true ) force no-cache. I reload the page to make "redirects normal effect" of HTML form when submit. You can manipulate DOM instead.
location.reload( true );
} else {
console.log( xhr.status, xhr.responseText );
}
}
xhr.send( body );
}
var deleteMethod = ( event ) => {
event.preventDefault();
var confirm = window.confirm( "Certeza em deletar este conteúdo?" );
if ( confirm ) {
var target = event.target;
while ( target.tagName != "FORM" ) {
target = target.parentElement;
}
var url = target.getAttribute( "action" );
var xhr = new XMLHttpRequest();
xhr.open( "DELETE", url );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = () => {
if ( xhr.status === 200 ) {
location.reload( true );
console.log( xhr.responseText );
} else {
console.log( xhr.status, xhr.responseText );
}
}
xhr.send();
}
}
</script>
With these functions defined, I add a event listener to the buttons which make the form method request:
<script>
document.querySelectorAll( "[name=update_data], [name=delete_data]" ).forEach( element => {
var button = element;
var form = element;
while ( form.tagName != "FORM" ) {
form = form.parentElement;
}
var method = form.getAttribute( "method" );
if ( method == "PUT" ) {
button.addEventListener( "click", putMethod );
}
if ( method == "DELETE" ) {
button.addEventListener( "click", deleteMethod );
}
} );
</script>
And for the remove button on the PUT form:
<script>
document.querySelectorAll( "[name=remove_data]" ).forEach( element => {
var button = element;
button.addEventListener( "click", deleteMethod );
</script>
_ - - - - - - - - - - -
This article https://blog.garstasio.com/you-dont-need-jquery/ajax/ helps me a lot!
Beyond this, you can set postMethod function and getMethod to handle POST and GET submit methods as you like instead browser default behavior. You can do whatever you want instead use location.reload(), like show message of successful changes or successful deletion.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
JSFiddle: https://jsfiddle.net/enriquerene/d6jvw52t/53/
If you are using nodejs, you can install the package method-override that lets you do this using a middleware.
Link to documentation: http://expressjs.com/en/resources/middleware/method-override.html
After installing this, all I had to do was the following:
var methodOverride = require('method-override')
app.use(methodOverride('_method'))
I wrote an npm package called 'html-form-enhancer'. By dropping it into your HTML source, it takes over submission of forms with methods aside from GET and POST, and also adds application/json serialization.
<script type=module" src="html-form-enhancer.js"></script>
<form method="PUT">
...
</form>
In simple words - No.
I have tried to fire a put request in the HTML form, but it sends the POST request to the server. To add the PUT request -
We can do it by listening to the submit action in the script, then fire the put request to a particular endpoint.
Screenshot from the http-server env. test
I am trying to assign different actions to same html form according to different submit buttons.
Can I do something like this ?
<FORM>
------
<INPUT type="submit" value="DoSomething" action="DoSomething.pl" method="POST">
<INPUT type="submit" value="DoSomethingElse" action="DoSomethingElse.pl" method="POST">
<FORM/>
Just in case someone else finds this post:
If you're using HTML5, this is now easier thanks to the formaction attribute. This attribute applies to input and button elements of type="submit" and forces the form to submit to the location specified in the formaction attribute of the clicked element.
Then only drawback of this attribute is that it's not supported by Internet Explorer 9 and lower, but this limitation can be easily overcome using a little JavaScript.
Example:
<form method="post" action="go_default">
<input type="submit" value="Go Left" formaction="go_left" />
<input type="submit" value="Go Right" formaction="go_right" />
</form>
For IE 9 and lower:
<script type="text/javascript">
$(function () {
var $submit = $('form [type="submit"][formaction]');
$submit.click(function() {
var $this = $(this),
action = $this.prop('formaction'),
$form = $this.closest('form');
$form.prop('action', action).submit();
});
});
</script>
No. A form has only one action (action being a property of the form, not the submit button).
The target of the action can do different things on the basis of the values in the form. So, you might want to start naming your submit buttons.
Learn HTML before you even think about writing and deploying a CGI script.
<form method="POST" action="/cgi-bin/script">
<input type="submit" name="action" value="DoSomething">
<input type="submit" name="action" value="DoSomethingElse">
</form>
Note also that choosing an action based on the value of the submit button is a losing strategy if you wish to internationalize the application because the value of a submit button is what the UA displays to humans.
Therefore, script should decide what to do on the basis of some other input element's value.
For example, CGI::Application looks at a run_mode parameter.
Alternatively, you can use different names for your submit buttons as Alec suggests. In that case, you need to check which submit button was pressed by going through the names of the parameters passed to your script which, IMHO, makes the dispatch slightly more cumbersome. It also means it is possible for someone to pass values for all submit buttons to your script (not via the user interface, but via curl or wget or similar programs.
For example, given the HTML
<form method="POST" action="/cgi-bin/script">
<input type="submit" name="submit_left" value="Go Left">
<input type="submit" name="submit_right" value="Go Right">
</form>
here is how your script may handle form submission:
#!/usr/bin/perl
use strict; use warnings;
use CGI::Simple;
my $cgi = CGI::Simple->new;
my %dispatch = (
left => \&handle_left,
right => \&handle_right,
);
my #actions = grep s/^action_(right|left)\z/$1/, $cgi->param;
my $handler = \&handle_invalid_action;
if ( #actions == 1) {
my ($action) = #actions;
if ( exists $dispatch{ $action } ) {
$handler = $dispatch{ $action };
}
}
else {
$handler = \&handle_too_many_actions;
}
$handler->($cgi);
sub handle_left { }
sub handle_right { }
sub handle_invalid_action { }
# because it may indicate someone trying to abuse your script
sub handle_too_many_actions { }
You can also use Ajax for this, and every button has assigned an ajax function that calls it's own php script and you don't even need to refresh the page or redirect, like in this example that i have tried:
HTML:
<input type="submit" value="Make other thing" onclick="ajax_post1();"/>
<input type="submit" value="Make something" onclick="ajax_post2();"/>
<div id="script1Response"></div>
<div id="script2Response"></div>
Javascript functions:
//the first function
function ajax_post1(){
var hr = new XMLHttpRequest();
//take the values from the html input elements you want to use
var v1=document.getElementbyId("element1").value;
var v2=document.getElementbyId("element2").value;
//the script that will process the data
var url="php_script1.php";
//the variable that will contain the information for the php script
var dataVar="var1="+v1+"&var2="+v2;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var script_response = hr.responseText;
document.getElementById("script1Response").innerHTML = script_response;
}
}
// Send the data to php_script1.php
hr.send(dataVar); // Actually execute the request
document.getElementById("script1Response").innerHTML = "processing...";
}
//the second function
function ajax_post2(){
var v1=document.getElementbyId("element1").value;
var v2=document.getElementbyId("element2").value;
var url="php_script2.php";
var dataVar="var1="+v1+"&var2="+v2;
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var script_response = hr.responseText;
document.getElementById("script2Response").innerHTML = script_response;
}
}
hr.send(dataVar);
document.getElementById("script2Response").innerHTML = "processing...";
}
The php files will have to contain some variables that will store the values sent by dataVar parameter like this:
$var1_=$_POST['var1']; //the var1 from the dataVar parameter
$var2_=$_POST['var2']; //the var2 from the dataVar parameter
The example I used can be found here:
https://www.youtube.com/watch?v=woNQ2MA_0XU.