recently I have been trying to install weceem 1.2-M1 plugin on grails but it just refuses to let me edit content. Whenever I try to edit content, a chunk of JS is served as text in the header of the page(sorry cant post pictures yet).
<script language="javascript" type="text/javascript"> function styleButtons() { $('button.removeTag').button({ icons: { primary: 'ui-icon-closethick' }, text: false }); } $(function() { styleButtons(); $('button.addTag').button(); /*{icons: { primary: 'ui-icon-plus' }});*/ $('#tagsfield_tags .addTag').click( function(event) { event.preventDefault(); var dataElem = $("input[name='tags']"); var existingTags = dataElem.val().split(','); var displayTagsParent = $("#tagsfield_tags .existingTagList"); var newTagsElem = $("input[name='newTags_tags']"); var newTags = newTagsElem.val().split(','); var exists = false; $.each(newTags, function(index, t) { t = $.trim(t).toLowerCase(); var exists = false for (i = 0; i < existingTags.length; i++) { if (existingTags[i] == t) { exists = true; break; } } if (!exists) { existingTags[existingTags.length] = t; $('<div class="existingTag"><span class="tagtext">'+t+'</span><button class="removeTag">Remove</button></div>').appendTo(displayTagsParent); styleButtons(); } }) dataElem.val(existingTags.join(',')); newTagsElem.val(''); }); $('#tagsfield_tags .removeTag').live('click', function(event) { event.preventDefault(); var tagParentDiv = $(event.target).parentsUntil('.existingTagList'); var tagToRemove = $('.tagtext', tagParentDiv).text(); $(tagParentDiv).fadeOut(500, function() { $(this).remove(); }); var dataElem = $("input[name='tags']"); var currentTags = dataElem.val().split(','); var newVal = ''; $.each(currentTags, function(index, t) { t = $.trim(t).toLowerCase(); if (t != tagToRemove) { newVal += t + ',' } }); dataElem.val(newVal); }); }); </script>
I have already included the 2 lines below into the Config file.
grails.resources.adhoc.excludes = ['/plugins/weceem-1.2-M1/*']
grails.mime.disable.accept.header.userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']
grails.mime.file.extensions = false
grails.mime.types = [ // the first one is the default format
all: '*/*', // 'all' maps to '*' or the first available format in withFormat
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
form: 'application/x-www-form-urlencoded',
html: ['text/html','application/xhtml+xml'],
js: 'text/javascript',
json: ['application/json', 'text/json'],
multipartForm: 'multipart/form-data',
rss: 'application/rss+xml',
text: 'text/plain',
hal: ['application/hal+json','application/hal+xml'],
xml: ['text/xml', 'application/xml']
]
grails.resources.adhoc.excludes = ['/plugins/weceem-1.2-M1/*']
//grails.resources.adhoc.patterns = ['/images/*', '/css/*', '/js/*', '/plugins/*']
and this is my buildconfig file
plugins {
checksums false
build ":tomcat:7.0.50"
compile ":twitter-bootstrap:3.1.0"
compile ":scaffolding:2.0.1"
compile ':cache:1.1.1'
compile ":jquery:1.8.3"
compile ":jquery-ui:1.8.24"
compile (':weceem:1.2-M1')
compile ":hibernate:3.6.10.7"
runtime ":database-migration:1.3.8"
compile ":resources:1.2.1"
runtime ":twitter-bootstrap:3.0.3"
}
and lastly, here is my urlmapping
class UrlMappings {
static mappings = {
// "/$controller/$action?/$id?(.$format)?"{
// constraints {
// // apply constraints here
// }
// }
//"/"(view:"/index")
"500"(view:'/error')
}
}
Con somebody help me figure out what's wrong or point me to the right direction? thank you so much!
What about your security settings for plugin? Maybe you don't have rights to edit content? You can check demo application with weceem plugin, see http://www.weceem.org/weceem/ or https://github.com/jCatalog/weceem-app for example of configuration.
Related
I have an issue with eval() in javascript code. Can someone help me in fixing the issue. Below is my code for adding menu buttons by using a loop.
for (var i = 0; i < organizedADMINMenuDetails.length; i++) {
var menuItem = Ext.create('Ext.button.Button', {
text: organizedADMINMenuDetails[i].menuName.toString().trim(),
itemId: organizedADMINMenuDetails[i].menuuid.toString().trim(),
iconCls: organizedADMINMenuDetails[i].iconcls.toString().trim(),
plain: true,
handler: function (self, e) {
hideNorthRegionMenuToolBars();
eval("fn_" + self.itemId + "();");
}
});
}
var fn_menuitem_Admin_Manager = function () {
var url = "";
tabDetails = {
tabId: 'ManagerReports',
title: 'Manager Reports',
url: url
}
top.mmdApp.navigation.openTab(tabDetails);
};
var fn_menuitem_Admin_PracticeSetup = function () {
var url = " ";
tabDetails = {
tabId: 'PracticeSetup',
title: 'Practice Setup',
url: url
}
top.mmdApp.navigation.openTab(tabDetails);
};
While minification, MVC changes the javascript function name to some hi, si or pi and when I do an eval(button id), the function is not found and my application is throwing an error. How can I resolve this issue? Please help...
I need to add drag and drop functionality to a SharePoint application for uploading files.
I'd like to use dropzone.js as it already has much of the functionality needed.
Everything must be handled in the browser, using SharePoint Services SOAP AJAX library.
Dropping files should automatically load them into a SharePoint Document Library.
Using Dropzone.js with SharePoint Services to upload files to a SharePoint Library.
This should work with IE 10+
First, the HTML:
<!doctype html>
<html>
<head>
<title>SharePoint Services w/ DropZone.js</title>
<link rel="stylesheet" type="text/css" href="/sites/test_acme_development/acmeApps/Lib/dropzone/dropzone.css">
</head>
<body>
<div id="dz" class='dropzone'></div>
<div id="message"></div>
<script type="text/javascript" src="/sites/test_acme_development/acmeApps/Lib/jquery1.11.3/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/sites/test_acme_development/acmeApps/Lib/SPServices2014.02/jquery.SPServices-2014.02.min.js"></script>
<script type="text/javascript" src="/sites/test_acme_development/acmeApps/Lib/dropzone/dropzone.js"></script>
<script type="text/javascript"> Dropzone.autoDiscover = false; /* Prevent Dropzone from doing auto stuff */ </script>
<script type="text/javascript" src="/sites/test_acme_development/acmeApps/App/uploadApp/js/upload.js"></script>
</body>
</html>
Notice this bit right after including dropzone.js:
Dropzone.autoDiscover = false;
It seems to work best when immediately stipulated like this.
The JavaScript:
(function (app, $, undefined) { }(window.app = window.app || {}, jQuery)); // setup app namespace
window.onload = function(e) { app.init(e); };
app.init = function(e) {
app.siteURL = 'https://portal.acme.com';
app.clientPath = '/sites/test_acme_development/';
app.fileLib = 'MySPLibrary';
app.loadDropzone();
};
app.loadDropzone = function() {
var dz = new Dropzone(document.getElementById("dz"), {
url: window.location.href,
autoProcessQueue: true,
uploadMultiple: true,
dictDefaultMessage: 'Drop files here or Click to select...'
});
dz.on("sendingmultiple", function(files, xhr, formData) {
for (var i = 0; i < files.length; i++) {
app.singleUpload(files[i], function() { /* upload done */ });
}
});
dz.on("queuecomplete", function () {
$('#message').html('Waiting for SharePoint to digest your files...').css('color', 'darkgreen');
setTimeout(function () {
$('#message').html('Done Loading Files into SharePoint...').css('color', 'darkgreen');
/* Continue doing stuff */
}, 8500);
});
};
app.singleUpload = function (readFile, cb) {
var reader = new FileReader();
var currFile = readFile;
reader.readAsArrayBuffer(currFile);
reader.onload = (function (theFile) { // (IIFE) Immediately-Invoked Function Expression
return function (e) {
var fileStream = app.aryBufferToBase64(e.target.result);
var destUrl = ['{0}{1}{2}/{3}'.f(app.siteURL, app.clientPath, app.fileLib, theFile.name)];
$().SPServices({
operation: "CopyIntoItems",
SourceUrl: null,
DestinationUrls: destUrl,
Stream: fileStream,
Fields: [],
completefunc: function (xData, Status) {
var err = $(xData.responseXML).find("CopyResult").first().attr("ErrorCode");
if (err && err === "Success") {
cb();
} else {
$('#message').html('Error: SharePoint Services failed during "singleUpload" process.').css('color', 'darkred');
}
}
});
};
})(currFile);
};
app.aryBufferToBase64 = function(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
};
String.prototype.f = function () { var args = arguments; return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; }); }; // like .net's string.format() function
I need to use excel-builder.js to export excel file with stylings(header background color blue, freezing top row, column filtering), but the website with all documentation is not accessible anymore, I even contacted the author but without response.
If anyone can help create a small example with all these formattings, I will appreciate it a lot!
I know the following code will build an excel file:
var jsonData = [
['sample', 'data', 'for'],
['generating', 'excel', 'in'],
['java', 'script', ' ']
];
require(['excel-builder.js/excel-builder', 'download'], function (EB, downloader) {
var JSworkBook = EB.createWorkbook();
var JSworkSheet = JSworkBook.createWorksheet({name: 'Sheet'});
JSworkSheet.setData(jsonData);
JSworkBook.addWorksheet(JSworkSheet);
var data = EB.createFile(JSworkBook);
downloader('Artist WB.xlsx', data);
});
You can access a cached version of the documentation via the web archive . Keep in mind though that you'll need to navigate between the pages of the documentation using the cached-url-syntax, instead of just clicking on the links.
I'm only adding this because the project is now declared dead (https://github.com/stephenliberty/excel-builder.js), and the website documentation is offline(http://excelbuilderjs.com/). So best we can do is find someone willing to take control of it with a fork, or share our code.
The server-side script..
<cfscript>
path="/app/uploads/temp/";
full_path=ExpandPath(path) & FORM.filename;
if (!DirectoryExists(ExpandPath(path))) DirectoryCreate(ExpandPath(path));
FileWrite(full_path,(BinaryDecode(FORM.contents,"Base64")));
json=StructNew();
json.file=path & FORM.filename;
WriteJSON(json);
</cfscript>
you could use PHP..
<?php
header("Content-type: ".$_POST['contentType']);
header("Content-disposition: attachment; filename=\"{$_POST['fileName']}\"");
echo base64_decode($_POST['contents']);
?>
or asp..
[Authorize]
[System.Web.Mvc.SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class SystemController : ApiController {
private ILog log = LogManager.GetLogger(typeof(SystemController));
public class ExcelResponse {
public String FILE = "";
}
public class ExcelRequest {
public String filename;
public String contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public String contents;
}
[HttpPost]
public ExcelResponse Excel(ExcelRequest request) {
ExcelResponse response = new ExcelResponse();
String the_path = "/_assets/temp/";
String path=System.Web.HttpContext.Current.Server.MapPath("~"+the_path);
log.Info("Generating excel file from data: "+path+request.filename);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
byte[] file_data=(Convert.FromBase64String(request.contents));
File.WriteAllBytes(path + request.filename, file_data);
response.FILE = the_path+request.filename;
return response;
}
}
And the include script...
require.config({
baseUrl: '/app/assets/',
paths: {
underscore: '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min',
JSZip: './excel-builder/jszip',
EB: './excel-builder.dist.min',
spin: '//cdnjs.cloudflare.com/ajax/libs/spin.js/1.2.7/spin.min',
image: '/3rdparty/requirejs/image',
text: '/3rdparty/requirejs/text',
util: '/excel-builder/Excel/util'
},
shim: {
'underscore': {
exports: '_'
},
'JSZip': {
exports: 'JSZip'
},
'swfobject': {
exports: 'swfObject'
}
}
});
goes into ./excel-builder/download.js
define(function () {
return function (fileName, content) {
var form = $("<form id='download'>").attr({
target: '_BLANK',
action: '/app/assets/excel-builder/excel.cfm',
method: 'post'
}).css({display: 'none'});
form.append($("<input>").attr({name: 'fileName', value: fileName}));
form.append($("<input>").attr({name: 'contentType', value: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
var ta=$("<textarea>").attr({name: 'contents', value: content});
ta.val(content);
form.append(ta);
form.appendTo($("body"));
form.submit();
window.setTimeout(function () {form.remove();}, 30000);
}
});
The bootstrap (for tablesorter)...
$(document).ready(function() {
$("table.sort").on("filterEnd",ts_onTableFiltered);
});
The meat of it...
function ts_onTableFiltered(event,tblsorter) {
$(tblsorter.table).data('ts_sorter',tblsorter);/*legacy :: */ window.ts_currentSorter=tblsorter;
console.log(event.type);
$(tblsorter.table).data('ts_isFiltered',false); /*legacy. remove me after verification :: */ window.ts_isFiltered=false;
for (var i=0;i<tblsorter.lastSearch.length;i++) {
var currentItemFilter=((tblsorter.lastSearch[i]!="")?true:false);
if (currentItemFilter) {
$(tblsorter.table).data('ts_isFiltered',true);/* legacy:: */ts_isFiltered=true;
break;
}
}
var rows=[];
if ($.isEmptyObject( tblsorter.cache )) {
rows=tblsorter.$tbodies.eq( 0 ).children( 'tr' );
} else {
for(i=0;i<tblsorter.cache[0].normalized.length;i++) {
var row=tblsorter.cache[0].normalized[i][tblsorter.columns].$row[0];
if (!ts_isFiltered) {rows.push($(row));continue;}
var result=tblsorter.pager.regexRows.test(row.className);
if (!result) { // skip 'filtered' className
rows.push($(row));
}
}
}
$(tblsorter.table).data('ts_currentRowsInTable',rows); /*legacy :: */window.ts_currentRowsInTable=rows;
console.log(rows.length);
}
function downloadExcelFromTable(tableObj,filename,props) {
var button=$('a:contains("Excel")');
if (button.length > 1) {
var temp=0;
button.each(function() {
if ($(this).attr('onclick').indexOf(tableObj.attr('id'))>=0) {
temp=$(this);
}
});
//button=temp;
}
console.log("Generating document...");
var orig_data = [];
var headers=[];
var headers_text_len_max=0;
var excel_wait_html='<i class="fa fa-spinner fa-pulse"></i> Please wait...';
button.data('orig-html',button.html());button.html(excel_wait_html);
if (tableObj.data('ts_currentRowsInTable').length<1 || (tableObj.data('ts_currentRowsInTable').length==1 && tableObj.find('tr:contains("No known")').length>0)) {
return BootstrapMessage("Cannot download Excel document","Sorry but there aren't any result rows to populate an excel document. Please refine your report/resultant listing.",function() {
button.html(button.data('orig-html'));
});
}
var doSetupProperties=false;
if (typeof(props)==='undefined') {props={};}
if (typeof(props.column_widths)==='undefined') {
doSetupProperties=true;
props.column_widths=[];
props.column_widths_auto=[];
props.maxWidthPerRow=[];
}
var filterChosen=false;
if (tableObj.hasClass("selectable")) filterChosen=true;
var ignoreCols=[];
var i=0;
tableObj.find('th').each(function() {
if ($(this).text().length<1) ignoreCols.push(i);
else {
headers.push($(this).text());
props.maxWidthPerRow.push(0);
headers_text_len_max+=$(this).text().length;
}
i++;
});
orig_data.push(headers);
console.log("Headers done.");
var handleRow=function(row,ignoreCols) {
var col_i=0;
row.find('td').each(function() {
if ($.inArray(col_i,ignoreCols)<0) {
var text=$(this).text().split('\n').join('').trim();
if ($(this).hasClass('sorter-select')) {
text=$(this).find('select:first').val();
}
var contents=text;
if (tableObj.hasClass('attachTotalsRow')) {
if ((''+tableObj.data('totals_columns')).indexOf(col_i+1)!=-1) {
text=(text.replace('$',''));
contents=parseFloat(text);
}
//row_data.push({value: text,metadata: {style: }});
//row_data.push(parseFloat(text));
}
row_data.push(contents);
var href=$(this).find('a');
if (href.length>0) {
var url=href.attr('href');
row_data[row_data.length-1]={value: 'HYPERLINK("'+url+'","'+text+'")', metadata: { type: 'formula' }};
}
if (text.length > props.maxWidthPerRow[col_i]) props.maxWidthPerRow[col_i]=text.length;
}
col_i++;
});
return (row_data);
}
if (tableObj.hasClass('tablesorter')) {
/*its tablesorter, so we need to obtain all of the hidden filtered data too. */
var rows=tableObj.data('ts_currentRowsInTable');
for (i=0;i<rows.length;i++) {
var row_data=[];
var row = $(rows[i]);
/*if (filterChosen && !isNaN(tableObj.data('chosen'))) {
var target=row.find('td:nth-child('+tableObj.data('chosen')+' input[type=checkbox]');
if (target.length==1) {
if (!target.prop('checked')) continue;
}
}*/
orig_data.push(handleRow(row,ignoreCols));
}
} else {
tableObj.find('tbody tr').each(function() {
var row_data=[];
var row=$(this);
orig_data.push(handleRow(row,ignoreCols));
});
}
if (tableObj.hasClass('attachTotalsRow')) {
var list_cols=tableObj.data('totals_columns');
if (isNaN(list_cols)) {
var av_cols=list_cols.split(',');
} else {
var av_cols=[list_cols];
}
av_cols=av_cols.sort();
var max=orig_data.length;
var min=2; // skip header row
var new_totals_row=[];
for (var ii=0;ii<headers.length;ii++) {
new_totals_row[ii]="";
}
for (var i=0;i<av_cols.length;i++) {
var colIdent=String.fromCharCode(64+av_cols[i]);
new_totals_row[0]="Totals:"
new_totals_row[av_cols[i]-1]={value: 'SUM('+((colIdent+min)+':'+(colIdent+max))+')',metadata: {type: 'formula'}};
}
orig_data.push(new_totals_row);
}
// adjust column widths to fit their text.
if (doSetupProperties) {
var maxDigitWidth=8;
var padding=22;
var fn_truncate=function(num) {return Math.round(num*100)/100;};
var fn_calcWidth=function(numchars,maxdigit,pad) {return fn_truncate(((numchars * maxdigit + pad)/maxdigit*256)/256 );};
var fn_calcPixels=function(p_width,maxdigit){return fn_truncate(((256 * p_width + fn_truncate(128/maxdigit))/256)*maxdigit);};
for (var i=0;i<headers.length;i++) {
var perc_size_of_whole=(100/headers_text_len_max)*headers[i].length;
//props.column_widths.push({width: perc_size_of_whole*1.5});
//props.column_widths_auto.push({bestFit: true,width: maxWidthPerRow[i]});
props.column_widths.push({width: (fn_calcWidth(props.maxWidthPerRow[i],maxDigitWidth,padding)) });
}
}
console.log(props);
console.log("Row data done.");
require(['excel-builder/excel-builder', 'excel-builder/Excel/Table','excel-builder/download'], function (EB, Table, downloader) {
console.log("Beginning excel creation.");
var workbook = EB.createWorkbook();
var worksheet = workbook.createWorksheet({name: filename});
var stylesheet = workbook.getStyleSheet();
var currency = stylesheet.createFormat({
format: '$#,##0.00'
});
var boldDXF = stylesheet.createDifferentialStyle({
font: {
italic: true,
size: 12
}
});
var sheetStyle=stylesheet.createTableStyle({
name: 'SlightlyOffColorBlue',
wholeTable: boldDXF.id,
headerRow: stylesheet.createDifferentialStyle({
alignment: {horizontal: 'center'},
font: {
size: 13,
bold: true
}
}).id
});
console.log("Styles applied.");
var table = new Table();
table.styleInfo.themeStyle = "SlightlyOffColorBlue"; //"TableStyleDark2"; //This is a predefined table style
table.setReferenceRange([1, 1], [headers.length, orig_data.length]); //X/Y position where the table starts and stops.
//Table columns are required, even if headerRowCount is zero. The name of the column also must match the
//data in the column cell that is the header - keep this in mind for localization
table.setTableColumns(headers);
console.log("headers configured.");
worksheet.setData(orig_data);
worksheet.setColumns(props.column_widths)
//worksheet.setColumnFormats(props.column_widths_auto);
workbook.addWorksheet(worksheet);
worksheet.addTable(table);
workbook.addTable(table);
console.log("tables configured.");
var dt=new Date();
var file= replaceAll(filename," ","_") +"_"+ (dt.getFullYear()+"-"+dt.getMonth()+"-"+dt.getDate()+"_"+dt.getMilliseconds())+'.xlsx';
file=replaceAll(file,"/","_"); file=replaceAll(file,"\\","_");
var data = EB.createFile(workbook);
console.log("workbook generated. File generation commensing: ");
//downloader(file, data); // this uses the downloader.js file. Disabled as I am customizing the ajax call completely... as follows..
/*legacy attempt.. var contents=''+
'<form method="POST" action="/app/assets/excel-builder/excel.cfm" enctype="application/x-www-form-urlencoded">'+
'<input type="hidden" name="filename" value="'+file+'" />'+
'<input type="hidden" name="contentType" value="'+('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')+'" />'+
'<input type="hidden" name="contents" value="'+data+'" />'+
'<input type="submit" value="Download Now" class="button print" />'+
'</form>';*/
var dat={
filename: file,
contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
contents: data
};
$.ajax({
url: '/app/assets/excel-builder/excel2.cfm',
type: "POST",
data: dat,
success: function(result) {
result=$.parseJSON(result);
console.log("Response received. File is located here: "+result.FILE);
if (typeof(onExcelDocGenerated)==='function') onExcelDocGenerated(); // optional callback (global)
contents='<a style="color: lightgreen;" href="'+result.FILE+'" class="button print" >Download Now</a>';
$.notice("Confirm Excel Download",contents,"Cancel",function() {
button.html(button.data('orig-html'));
if (typeof(excel_download_done)==='function') {
excel_download_done(); // optional callback (global)
}
},function() {
button.html(button.data('orig-html'));
if (typeof(excel_download_done)==='function') {
excel_download_done();
}
});
},
error: function(e) {
console.log("Fatal networking error: "+e);
}
});
});
}
And the implementation on the page..
<a href="#" id="exceldownload" onclick="try {downloadExcelFromTable($('table'),'My Report');}catch(e){alert('failed due to error: '+e);};return false;" class="button print table-excel">
<i class="fa fa-file-excel-o"></i> Excel
</a>
So that was a tablesorter full implementation supporting links inserted into the excel sheet and even a row for summation (totals) by simply adding the class(.attachTotalsRow) to the table class attr.
Even supports filtering, so it only grabs the rows that are filtered by tablesorter for the excel, and auto-column sizing based on text width.
There's several pieces that you can see were being developed, and lots of sparse comments and console logs thrown about, but it works.
The above is designed for the ajax call which provides a path to a file in JSON response. That way you can use the browser native click, which is supported on all devices. Opening a new window through javascript is unsafe, so that is the reason for that approach. Therefore the php script at the top would need updated to mimic the coldfusion one.
The part you wanted is at the bottom just before the ajax call.
Good luck!
var workbook = ExcelBuilder.Builder.createWorkbook();
var stylesheet = workbook.getStyleSheet();
var sheet1 = workbook.createWorksheet({
name: 'Data1'
});
var headings = stylesheet.createFormat({
"fill": {
"type": 'pattern',
"patternType": 'solid',
"fgColor": '4BACC6'
}
});
var jsonData = [
[{value:'sample', metadata: {style: headings.id}}, {value:'data', metadata: {style: headings.id}}, {value:'for', metadata: {style: headings.id}}],
['generating', 'excel', 'in'],
['java', 'script', ' ']
];
sheet1.setData(jsonData);
workbook.addWorksheet(sheet1);
ExcelBuilder.Builder.createFile(workbook, {
type: "blob"
}).then(function(data) {
saveAs(new Blob([data], {
type: "base64"
}), "Demo.xlsx");
});
Quick background: Very new to web development. I have a bootstrap page with a form which users can fill out. There are four fields (two text boxes, one radio, one dropdown). The idea was to form a JSON using that input data and POST it to my HTTP server, but it doesn't seem to be working anymore.
Very strange, my code was working perfectly a few hours ago (have been testing with requestb.in).
Now all of a sudden it (1) only sends the POST if I have long values for the apiname and apiurl variables, and (2) no longer sees what I've chosen from the radio checkboxes (env1 - env3), and instead always thinks I've chosen 'Dev,' regardless of what was actually selected.
I'm assuming my issues are caused by the jQuery in my code and not the HTML, so I've attached that here:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("button").click(function(){
var env1 = document.getElementById("seldevid");
var env2 = document.getElementById("selstageid");
var env3 = document.getElementById("selprodid");
var apiname = $("#apinameid").val();
var apiurl = $("#apiurlid").val();
var actionvar;
$("#actionid").change(function() {
actionvar = $(this).val();
}).change();
if (env1.checked = true) {
var env = "Dev";
} else if (env2.checked = true) {
var env = "Stage";
} else if (env3.checked = true) {
var env = "Prod";
}
$.post("http://requestb.in/107fmof1",
{
apiName: apiname,
apiURL: apiurl,
environment: env,
action: actionvar
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
Thanks for the help!
First Question: Why Always "Dev"?
The issue is in your if statements you have used an assignment, rather than a boolean comparison. You need to use == to compare the two values for equality. Instead you are setting env1.checked = true, which evaluates to true, so env is always being set to "Dev".
if (env1.checked == true) {
var env = "Dev";
} else if (env2.checked == true) {
var env = "Stage";
} else if (env3.checked == true) {
var env = "Prod";
}
or even
var env;
if (env1.checked) {
env = "Dev";
} else if (env2.checked) {
env = "Stage";
} else if (env3.checked) {
env = "Prod";
}
Second Question: Why not posting?
You should try simplifying your code a bit:
$(document).ready(function(){
var env1 = document.getElementById("seldevid");
var env2 = document.getElementById("selstageid");
var env3 = document.getElementById("selprodid");
$("button").click(function(){
var env = "Dev";
if (env2.checked) {
env = "Stage";
} else if (env3.checked) {
env = "Prod";
}
$.post("http://requestb.in/107fmof1",
{
apiName: $("#apinameid").val(),
apiURL: $("#apiurlid").val(),
environment: env,
action: $("#actionid").val()
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
}
);
});
});
Then using the browser Developer Tools to see what exactly is being POST'd, if anything.
I uses elFinder laravel package file Manager with ckeditor. I follow all Instructions step and all things work except one.
When I click on image button in ckEditor to select (or upload) an Image , on the upload tab after select an image from my computer and click Send it to the Server button NotFoundHttpException in RouteCollection.php line 161 shown and upload fails.
this is ckEditor initialization code :
<textarea name="content_fa" id="fa_post_content" class="form-control"
rows="10"></textarea>
<script>
var fa_post_content = CKEDITOR.replace('fa_post_content', {
toolbar: 'admin_mode',
filebrowserBrowseUrl : '{{route('elfinder.ckeditor')}}',
filebrowserUploadUrl : '/elfinder/connector.php?cmd=upload'
});
</script>
According to This Issue , I add filebrowserUploadUrl option as you see above. but this not work too.
How can I solve this ?
This code (+ DnD upload) using demo site is here.
CKEDITOR.on('dialogDefinition', function (event) {
var editor = event.editor,
dialogDefinition = event.data.definition,
tabCount = dialogDefinition.contents.length,
uploadButton, submitButton, inputId,
elfUrl = editor.config.filebrowserUploadUrl,
// elFinder configs
elfDirHashMap = { // Dialog name / elFinder holder hash Map
image : '',
flash : '',
files : '',
link : '',
fb : 'l1_Lw' // fallback target
},
customData = {}; // any custom data to post
for (var i = 0; i < tabCount; i++) {
uploadButton = dialogDefinition.contents[i].get('upload');
submitButton = dialogDefinition.contents[i].get('uploadButton');
if (uploadButton !== null && submitButton !== null) {
uploadButton.hidden = false;
submitButton.hidden = false;
uploadButton.onChange = function() {
inputId = this.domId;
}
submitButton.onClick = function(e) {
dialogName = CKEDITOR.dialog.getCurrent()._.name;
var target = elfDirHashMap[dialogName]? elfDirHashMap[dialogName] : elfDirHashMap['fb'],
name = $('#'+inputId),
input = name.find('iframe').contents().find('form').find('input:file'),
error = function(err) {
alert(err.replace('<br>', '\n'));
};
if (input.val()) {
var fd = new FormData();
fd.append('cmd', 'upload');
fd.append('overwrite', 0); // disable upload overwrite to make to increment file name
fd.append('target', target);
$.each(customData, function(key, val) {
fd.append(key, val);
});
fd.append('upload[]', input[0].files[0]);
$.ajax({
url: elfUrl,
type: 'POST',
data: fd,
processData: false,
contentType: false,
dataType: 'json'
})
.done(function( data ) {
if (data.added && data.added[0]) {
var url = data.added[0].url;
var dialog = CKEDITOR.dialog.getCurrent();
if (dialogName == 'image') {
var urlObj = 'txtUrl'
} else if (dialogName == 'flash') {
var urlObj = 'src'
} else if (dialogName == 'files' || dialogName == 'link') {
var urlObj = 'url'
} else {
return;
}
dialog.selectPage('info');
dialog.setValueOf(dialog._.currentTabId, urlObj, url);
} else {
error(data.error || data.warning || 'errUploadFile');
}
})
.fail(function() {
error('errUploadFile');
})
.always(function() {
input.val('');
});
}
return false;
}
}
}
});
For anyone running into this issue now, the thing that resolved it for me was setting filebrowserBrowseUrl. The mistake I was making was setting filebrowserUploadUrl instead of the filebrowserBrowseUrl. Elfinder handles the upload inside itself, so you should not have to use the 'send to the server' button at all, just the browse server button.
So the ckeditor code looked like such
CKEDITOR.replace('your-id-here', {
filebrowserBrowseUrl: '/elfinder/ckeditor',
}
);
noting to replace your-id-here with your own id.