ExtJS submit form to download file - javascript

Having a really hard time figuring this out. I need to submit a form in an ExtJS application and then download the data in a .CSV file. The problem is, the way ExtJS has me submitting the form with "isUpload" the parameters I'm POSTing are being sent as "mulitpart/form-data" and I can't consume them or parse them. I have multiple values of the same input field name.
field: A
field: B
field: C
When I submit for my grids they go over as multiple instances like above. As soon as I introduce "isUpload" to the form they go overs as:
field: A,B,C
My program reads field as "A,B,C" and not three separate instances of field!
Here's my code. Interesting that when I examine in Firebug the Params tab looks correct, but the POST tab has then all in one value.
I just recently added the parameters to the url to try and fake it out!
Ext.Ajax.request({
url : '/cgi-bin/cgijson007.pgm' + '?' + parameters,
form : myForm,
params : parameters,
standardSubmit : true,
isUpload : true
});

isUpload: true only defines that you want to upload a file along with fields, so multipart is correct. To download I recommend you to use a hidden frame. For that use a helper defined within a Namespace.
helper.util.HiddenForm = function(url,fields){
if (!Ext.isArray(fields))
return;
var body = Ext.getBody(),
frame = body.createChild({
tag:'iframe',
cls:'x-hidden',
id:'hiddenform-iframe',
name:'iframe'
}),
form = body.createChild({
tag:'form',
cls:'x-hidden',
id:'hiddenform-form',
action: url,
target:'iframe'
});
Ext.each(fields, function(el,i){
if (!Ext.isArray(el))
return false;
form.createChild({
tag:'input',
type:'text',
cls:'x-hidden',
id: 'hiddenform-' + el[0],
name: el[0],
value: el[1]
});
});
form.dom.submit();
return frame;
}
// Use it like
helper.util.HiddenForm('my/realtive/path', [["fieldname","fieldValue"]]);
If the server answer with a download the save window will popup.

Below is how I handler a post download on a grid listing:
First, I create html form container with hidden filed contains the parameters to post, and also a submit function.
var txtFileId = Ext.create('Ext.form.field.Hidden', { name: 'fid', value: 0 });
var dwFrm = Ext.create('Ext.container.Container', {
autoEl: { tag: 'form', method: 'POST', target: '_BLANK',
action: '/download/files' }, style: { hidden: true },
items: [txtFileId, {
xtype: 'hidden', name: 'userId', value: '1111'
}],
submit: function (fid) {
if (fid) {
txtFileId.setValue(fid);
this.el.dom.submit();
}
}
});
Second, I dock the above component into grid's toolbar
var grid = Ext.create('Ext.grid.Panel', {
.....
dockedItems: [Ext.create("Ext.Toolbar", {
dock: "top", items: [
dwFrm,
{ text: "Download Selected",
handler: function () {
var sm = grid.getSelectionModel();
if (!sm.hasSelection()) return null;
var recs = sm.getSelection();
dwFrm.submit(recs.data.id);
}
}
]
})]
.....
});

This works perfectly. Arrays included.
downloadFile: function (url, params) {
debugger;
var body = Ext.getBody(),
frame = body.createChild({
tag: 'iframe',
cls: 'x-hidden',
id: 'hiddenform-iframe',
name: 'iframe'
}),
form = body.createChild({
tag: 'form',
method: 'POST',
cls: 'x-hidden',
id: 'hiddenform-form',
action: url,
target: 'iframe'
});
for (var i in params) {
if (Ext.isArray(params[i])) {
for (var j = 0; j < params[i].length; j++) {
form.createChild({
tag: 'input',
type: 'hidden',
cls: 'x-hidden',
id: 'hiddenform-' + i,
name: i,
value: params[i][j]
});
}
} else {
form.createChild({
tag: 'input',
type: 'hidden',
cls: 'x-hidden',
id: 'hiddenform-' + i,
name: i,
value: params[i]
});
}
}
form.dom.submit();
return frame;
}

Related

ExtJS 7.1 Tag field is executing XSS tag

I am having an issue regarding the tagfield component when entering <img src=a onerror=alert('xss!')>. This tag is being executed after entering the whole value. I've tried preventing the tag execution on keyup, keypress, keydown, and beforequery events and it still executing. This block of code prevent the event from executing when it detects an XSS tag.
Ext.application({
name: 'Fiddle',
launch: function () {
var shows = Ext.create('Ext.data.Store', {
fields: ['id', 'show'],
data: []
});
Ext.create('Ext.form.Panel', {
renderTo: Ext.getBody(),
title: 'Sci-Fi Television',
height: 200,
width: 500,
items: [{
xtype: 'tagfield',
itemId: 'tagField',
fieldLabel: 'Select a Show',
store: shows,
displayField: 'show',
valueField: 'id',
queryMode: 'local',
filterPickList: false,
listeners: {
beforequery: function () {
var editor = Ext.ComponentQuery.query('#tagField')[0];
if (editor.inputEl.getValue().search(new RegExp('(<([^>]+)>)')) >= 0) {
editor.inputEl.dom.value = '';
return false;
}
},
keypress: function (textfield, event) {
var editor = Ext.ComponentQuery.query('#tagField')[0];
if (editor.inputEl.getValue().search(new RegExp('(<([^>]+)>)')) >= 0) {
editor.inputEl.dom.value = '';
return false;
}
},
keydown: function (textfield, event) {
var editor = Ext.ComponentQuery.query('#tagField')[0];
if (editor.inputEl.getValue().search(new RegExp('(<([^>]+)>)')) >= 0) {
editor.inputEl.dom.value = '';
return false;
}
},
}
}]
});
}
});
enter image description here
This took a little while to hunt down, but apparently in Ext.form.field.ComboBox, there's an onFieldMutation handler that really is the key to all of this. Take a look at this Fiddle and the code that takes care of handling this... I believe this is what you're looking for:
Ext.define('ComboOverride', {
override: 'Ext.form.field.ComboBox',
onFieldMutation: function (e) {
var inputDom = this.inputEl.dom;
if (Ext.String.hasHtmlCharacters(inputDom.value)) {
inputDom.value = '';
alert('XSS Detected, Removing');
}
return this.callParent(arguments);
}
});

ExtJs form multiple button for different binding

Need to bind my form elements separately for different buttons. Using allowBlank in elements for sending binding conditions and formBind in buttons for binding the buttons. Need to do this like in this simplest way. (ExtJs 4.2.1 Classic)
Example
Ext.create('Ext.form.Panel', {
......
items: [
Ext.create('Ext.form.field.Date', {
.....,
allowBlank: false, //bind for both search & download button.
.....
}),
......, //// All rest elements bind for both search & download button.
Ext.create('Ext.form.ComboBox', {
......,
allowBlank: false, //bind for only download button.
......
})
],
buttons: [
{
text: 'Search',
formBind: true, /// Need to bind for specific field only.
},
{
text: 'Download',
formBind: true, /// Need to bind for all.
},
............
});
If any other data or details is necessary then please don't hesitate to ask.
I created a fiddle here that I think should accomplish what you're trying to do. The idea to use an event listener on the combobox, instead of the formBind config of the Download button:
https://fiddle.sencha.com/#view/editor&fiddle/289a
Ext.create('Ext.form.Panel', {
renderTo: Ext.getBody(),
itemId: 'exampleForm',
items: [Ext.create('Ext.form.field.Date', {
allowBlank: false, //bind for both search & download button.
}),
Ext.create('Ext.form.ComboBox', {
allowBlank: false, //bind for only download button.
listeners: {
change: function (thisCombo, newValue, oldValue, eOpts) {
if (Ext.isEmpty(newValue)) {
thisCombo.up('#exampleForm').down('#btnDownload').setDisabled(true);
} else {
thisCombo.up('#exampleForm').down('#btnDownload').setDisabled(false);
}
}
},
store: ['item1', 'item2']
})
],
buttons: [{
text: 'Search',
formBind: true, /// Need to bind for specific field only.
}, {
itemId: 'btnDownload',
text: 'Download',
disabled: true
//formBind: true, /// Need to bind for all.
}]
});
There is no standard quick way to do this, you might want to write a plugin for this. I've put together one:
Ext.define('App.plugin.MultiDisableBind', {
extend: 'Ext.AbstractPlugin',
alias: 'plugin.multidisablebind',
/**
* #cfg
* Reference to the fields that this button depends on.
* Can contain either direct references, or a query selectors that will be
* executed with the button as the root
*/
depFields: null,
/**
* #property
* A map object with field ids as key, and field values as value
*/
valuesMap: null,
init: function (cmp) {
this.setCmp(cmp);
cmp.on('render', this.setup, this);
},
setup: function () {
var cmp = this.getCmp(),
depFields = this.depFields,
valuesMap = {};
if (!Ext.isArray(depFields)) {
depFields = [depFields];
}
Ext.Array.forEach(depFields, function (field) {
if (Ext.isString(field)) {
field = cmp.query(field)[0];
}
cmp.mon(
field,
'change',
Ext.Function.createThrottled(this.updateValuesMap, 300, this),
this
);
valuesMap[field.getId()] = field.getValue();
}, this);
this.valuesMap = valuesMap;
this.updateCmpDisabled();
},
updateValuesMap: function (depField, newValue) {
this.valuesMap[depField.getId()] = newValue;
this.updateCmpDisabled();
},
updateCmpDisabled: function () {
var cmp = this.getCmp(),
toDisable = true;
Ext.Object.each(this.valuesMap, function (fieldId, fieldValue) {
if (!Ext.isEmpty(fieldValue)) {
toDisable = false;
return false
}
});
cmp.setDisabled(toDisable);
}
});
You can use this plugin in your buttons like so:
xtype: 'button',
text: 'My button',
plugins: {
ptype: 'multidisablebind',
depFields: ['^form #fieldQuery', fieldVar]
}
In the depFields config you specify references to the fields that button's disabled state depends on, and the plugin will monitor these fields, so that on each field value change it will update the disabled state.
Here is a working fiddle: https://fiddle.sencha.com/#view/editor&fiddle/28cm
I have created a fiddle for you. The code uses bind and formBind respectively for the two different buttons. May be you want something like this.

Updating server from Kendo Color picker inside kendo grid

The Problem
So i am currently trying to implement a color picker inside of a Kendo grid, that will hopefully send the chosen color to my Sql Table. Unfortunately, It doesn't seem as though the Update controller is being reached. I am relatively new to Kendo UI, so there might be some incredibly dumb errors shown.
Questions
I guess my main question would be: How can i call the update method when update is clicked on the grid. Essentially, the color picker and the edit command are showing up in beautiful fashion. I just want to know how i can be sure that the method is being called when 'Update' is clicked, seeing as it is not reaching my controller. Feel free to ask if you need to see more code or perhaps a screen shot.
Code
Config.cshtml ( Grid )
#model IEnumerable<STZN.Models.AGCData.ErrorCode>
#{
ViewBag.Title = "Config";
}
#section HeadContent{
<script src="~/Scripts/common.js"></script>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
editable: "inline",
selectable: "row",
dataSource: {
schema: {
model: {
id: "error_code",
fields: {
color: { type: 'string' }
}
}
},
transport: {
read: {
type: "POST",
dataType: "json",
url: "#Url.Action("ErrorCodes")"
},
update: {
type: "POST" ,
dataType: "json",
url: "#Url.Action("UpdateErrorCodes")",
}
}
},
columns: [
{ command : [ "edit" ] },
{
field: "error_code", title: "Error Code",
},
{
field: "error_description", title: "Error Description"
},
{
field: "color",
width: 150,
title: "Color",
template: function (dataItem) {
return "<div style = 'background-color: " + dataItem.color + ";' </div>"
},
editor: function (container, options) {
var input = $("<input/>");
input.attr("color",options.field);
input.appendTo(container);
input.kendoColorPicker({
value: options.model.color,
buttons: false
})
},
}
]
});
});
</script>
}
Update Controller
public JsonResult UpdateErrorCodes(ErrorCode model)
{
using (var db = new AgcDBEntities())
{
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
db.Configuration.ProxyCreationEnabled = false;
var data = db.ErrorCodes.Where(d => d.error_code == model.error_code).Select(x => new
{
error_code = x.error_code,
description = x.error_description,
color = x.color,
});
return new JsonResult()
{
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
};
}
}
I actually managed to fix my issue by adding an additional input attribute to my editor function in the "color" field. It looks like this:
input.attr("data-bind","value:" + options.field);
There are still some present issues (unrelated to the fix/server update) , but as far as updating to the server, It work's as intended.

Onclick event of button placed in each row jqgrid not firing?

Situation : My app carries out an AJAX request and the data received is displayed in the following JQgrid . listData(data) is a function that is called in success call back of this ajax request ,
data is the JSON data received from request .
buildJqGrid is a custom function that calls the .jqgrid() on a table and div html element .
buttonFormatter is my custom formatter for the column named Action
function listData(data) {
var containerName = 'datatablea3',
columnNames = ["Name",
"Email",
"Language",
"Office",
"alter email",
"Action"
],
columnModels = [{
name: 'Name',
index: 'Name',
width: '200px'
},{
name: 'Email',
index: 'Email',
width: '200px'
}, {
name: 'Language',
index: 'Language',
width: '200px'
}, {
name: 'Office',
index: 'Office',
width: '200px'
}, {
name: 'AlterEmail',
index: 'AlterEmail',
width: '200px'
}, {
name: 'action',
width: '200px',
formatter: buttonFormatter
}],
sortColumnName = 'Name',
caption = "Employees",
rowNum = 25,
pager = '#pager2a3',
grouping = false,
groupingView = {},
rowList = [25, 50, 100];
buildJqGrid(containerName, data, columnNames, columnModels,
sortColumnName, caption, rowNum, pager, grouping,
groupingView, rowList, true, 'asc');
}
Problem : When this jsp is run data is successfully displayed in the jqgrid with view button in each record , but when i click on the view button nothing happens !.
I checked in console it shows "control in formatter" but on clicking view button it doesn't show "control in click function".
i also tried using editLink formatter but still same error there ,
Can anyone please tell me why my button's onclick event is not firing ?
"click" is already a function, and therefore you override it, and nothing fires.
Try this
function buttonFormatter(cellvalue, options, rowObject)
{
console.log("control in button formatter");
return '<button onclick=\"clickFunction();\">View</button>';
}
function clickFunction()
{
console.log("control in click function");
alert("hello");
}
Simple fiddle : https://jsfiddle.net/virginieLGB/5e5LL5po/1/
try like this, I also use same functionality(JQ Grid) in my project, try HTML input type rather than the button,
When using your code, click event was firing but the whole web page is reloading.
function buttonFormatter(cellvalue, options, rowObject) {
if (rowObject.Status != "Not Started") {
console.log("Zumbaa");
var edit = "<input class='Viewbtn' type='button' value='View' onclick=\"ShowMigrationProcess(" + cellvalue + ");\" />";
return edit;
}
return '';
}

How to create a WinJS Flyout via Javascript

Currently I have a toolbar with some buttons, here is how I create it :
HTML
<div id="toolbarContainer1" style="direction: rtl"></div>
Javascript
var dataArray= [
new WinJS.UI.Command(null, { id: 'cmdView3', label: 'View3', section: 'primary', type: 'button', icon: 'stop', tooltip: 'View 3', onclick: function () { changeView('view3') } }),
new WinJS.UI.Command(null, { id: 'cmdView2', label: 'View2', section: 'primary', type: 'button', icon: 'stop', tooltip: 'View 2', onclick: function () { changeView('view2') } }),
new WinJS.UI.Command(null, { id: 'cmdView1', label: 'View1', section: 'primary', type: 'button', icon: 'stop', tooltip: 'View 1', onclick: function () { changeView('view1') } })
];
window.createImperativeToolBar = function () {
var tb = new WinJS.UI.ToolBar(document.querySelector("#toolbarContainer1"), {
data: new WinJS.Binding.List(dataArray)
});
var thisToolbar = document.querySelector('#toolbarContainer1');
thisToolbar.winControl.closedDisplayMode = 'full';
}
I've tried doing adding it like so :
new WinJS.UI.Flyout(null, { id: 'formatTextFlyout', section: 'primary' })
It gets appended to the DOM but it looks like the options aren't working. The div (flyout) in the dom has no id as I've set above.
I want to show the flyout on button click :
function showFlyout() {
console.log('flyout');
var formatTextButton = document.getElementById("formatTextButton");
document.getElementById("formatTextFlyout").winControl.show(formatTextButton);
}
But obviously because the ID doesn't get set, an error gets logged. Any ideas ?
Here is a fiddle of what I have tried : https://jsfiddle.net/reko91/yg0rs4xc/1/
When you create a win-control like so:
new WinJS.UI.Flyout(null, { id: 'formatTextFlyout', section: 'primary' })
The id "formatTextFlyout" is only the the id of this flyout control.
But you use document.getElementById("formatTextFlyout") method to find this control, the problem is here, this method can only find the html element object with the Id "formatTextFlyout", and there is no one. You can refer to getElementById method.
One solution here is you create a Flyout like so:
HTML:
<div id="flyoutContainer"></div>
Javascript:
var flyout = new WinJS.UI.Flyout(document.querySelector("#flyoutContainer"), { id: 'formatTextFlyout', section: 'primary' });
function showFlyout() {
console.log('flyout');
var formatTextButton = document.getElementById("formatTextButton");
document.getElementById("flyoutContainer").winControl.show(formatTextButton);
}
Or
var flyout = new WinJS.UI.Flyout(document.querySelector("#flyoutContainer"), { id: 'formatTextFlyout', section: 'primary' });
function showFlyout() {
console.log('flyout');
var formatTextButton = document.getElementById("formatTextButton");
flyout.show(selectedButton);
}
If you read the sample of WinJS.UI.Flyout object there, you will find in html file, it creates a Flyout like so:
<div id="formatTextFlyout" data-win-control="WinJS.UI.Flyout"
aria-label="{Format text flyout}">
The html element is div and has a id "formatTextFlyout".
Addition: In the website Try WinJS, there are a lot of win-control samples which written with html+javascript+css.

Categories