output an image with javascript but not download - javascript

I use the library Highcharts in order to generate some graphics.
I would like to send them to the server and also to do a mysql request in order to save the data informations into my database. The thing is that It just download the file into my compuer.
I really would like to keep it on the server on a predefined folder. It just dowload it.
I wrote this code with many efforts.
I met many problems but I don't know how to pass this last.
Here is the code for generating the image and to download it auomatically:
<script type="text/javascript">//<![CDATA[
$(function(){
/**
* Create a global getSVG method that takes an array of charts as an argument
*/
Highcharts.getSVG = function(charts) {
var svgArr = [],
top = 0,
width = 0;
$.each(charts, function(i, chart) {
var svg = chart.getSVG();
svg = svg.replace('<svg', '<g transform="translate(0,' + top + ')" ');
svg = svg.replace('</svg>', '</g>');
top += chart.chartHeight;
width = Math.max(width, chart.chartWidth);
svgArr.push(svg);
});
return '<svg height="2400px" width="1200px" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>';
};
/**
* Create a global exportCharts method that takes an array of charts as an argument,
* and exporting options as the second argument
*/
Highcharts.exportCharts = function(charts, options) {
var form
svg = Highcharts.getSVG(charts);
// merge the options
options = Highcharts.merge(Highcharts.getOptions().exporting, options);
// create the form
form = Highcharts.createElement('form', {
method: 'post',
action: options.url
}, {
display: 'none'
}, document.body);
// add the values
Highcharts.each(['filename', 'type', 'width', 'svg'], function(name) {
Highcharts.createElement('input', {
type: 'hidden',
name: name,
value: {
filename: options.filename || 'chart',
type: options.type,
width: 1200,
svg: svg
}[name]
}, null, form);
});
//console.log(svg); return;
// submit
form.submit();
// clean up
form.parentNode.removeChild(form);
};
$('#export').click(function() {
Highcharts.exportCharts([chart1, chart2, chart3]);
});
});//]]>
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script type="text/javascript" src="http://highcharts.com/js/testing-exporting.js"></script>
<div id="container" style="height: 400px; width:1200px"></div>
<div id="container2" style="height: 400px; width:1200px"></div>
<div id="container3" style="height: 400px; width:1200px"></div>
<button id="export">Export all</button>
I just try to send it to to server.
Thank you all verry much in advance for the help.
Receive my Utmost Respect.
Kind Regards SP.

you can try this
var chart = $('#yourchart').highcharts();
svg = chart.getSVG();
var base_image = new Image();
svg = "data:image/svg+xml,"+svg;
base_image.src = svg;
$('#mock').attr('src', svg);
var dataString = $('#mock').html() ; // or just binary code
$.ajax({
type: 'POST',
data: dataString,
url: 'your-server/',
success: function(data){
}
});
Save highchart as binary image

Related

python django - Images are blank when written using decoded base64

My django website aims at allowing users to combine different clothing picture on one single canvas.
However, the saved image is blank.
I have applied one fiddle, please see here.
I've used the methods recommended by some forums.
Here is the views.py
#csrf_protect
#csrf_exempt
def savewearingimg(request):
imgEncodeString = request.POST.get('imgBase64')
if request.method == 'POST' and request.is_ajax():
singleItemNames = request.POST.getlist('singleItemNames[]')
saveWearingName = request.POST.get('saveWearingName') #string
positionsX = request.POST.getlist('positionsX[]')
positionsY = request.POST.getlist('positionsY[]')
userWidths = request.POST.getlist('sizes[]')
imgEncodeString = request.POST.get('imgBase64').partition(",")[2]#for header removing
img64Data = base64.b64decode(imgEncodeString) #other decoding fundctions failed
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
preFileStr = os.path.join(BASE_DIR, "media\\photos\\wearing\\")
poFileStr=str(request.user)+'_itemName_'+saveWearingName+'.jpg'
filename = preFileStr +poFileStr
with open(filename, 'wb') as f:
f.write(img64Data)
return render(request,'combinewearing.html')
And here is part of the javascript combinewearing.js
$(function() {
canvas = document.getElementById('save-canvas');
context = canvas.getContext('2d');
});
$('#saveWearingBtn').click(function(){
drawToSave(alreadyPutImg,originalWidths);
});
function drawToSave(alreadyPutImg,originalWidths){
loadImagesMike(sources, function(images_) { //the original author is Mike
for(var i=0; i<ImgPutArr.length; i++ ){
var img_iter = ImgPutArr[i];
context.drawImage(images_[i],img_iter.x,img_iter.y,img_iter.w,img_iter.h);
console.log('images_[i]: '+images_[i] );//[object HTMLImageElement]
i++;
}
});
var myDataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "/savewearingimg/",
data: {
'csrfmiddlewaretoken': "{{ csrf_token }}",
'imgBase64': myDataURL,
'singleItemNames': alreadyPutName,//array storing what users have added to the canvas
'saveWearingName':$('#saveWearingName').val(), //end-users can customized his/her desired wearing title
'positionsX':positionsX, //position array storing every clothing pictures
'positionsY':positionsY,
'sizes':sizes,
},
}).done(function(o) {
alert('saved');
console.log('saved');
});/*end ajax*/
}
/*sources is an array storing all the user-selected pictures absolute path*/
function loadImagesMike(sources, callback) {
var images = [];
var loadedImages = 0;
var numImages = 0;
// get num of sources
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
There is no error message. Only the image is blank.
However, if I follow the same steps and same string as this linksuggests, the image would not be blank.
So I suppose that the problem is due to the string's content. My failed
string content links to this google doc link(Correct me if I'm wrong, thank you.)
I've just found that this rectangle will show up in the image....
So what should I adjust?
context.rect(20, 20, 150, 100);
context.stroke();
I have solved this problem by moving THIS PART to the interior of the loadImagesMike() function (inside drawToSave())
THIS PART---->
var myDataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "/savewearingimg/",
data: {
'csrfmiddlewaretoken': "{{ csrf_token }}",
'imgBase64': myDataURL,
'singleItemNames': alreadyPutName,//array storing what users have added to the canvas
'saveWearingName':$('#saveWearingName').val(), //end-users can customized his/her desired wearing title
'positionsX':positionsX, //position array storing every clothing pictures
'positionsY':positionsY,
'sizes':sizes,
},
}).done(function(o) {
alert('saved');
console.log('saved');
});/*end ajax*/
THIS PART is moved after the for loop, and it is inside the loadImagesMike() function.

Displaying Project Oxford's Emotion API result

I've managed to run the following code thanks to this post here Adding Microsoft's Emotion API to HTML website.
<HTML>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","my-key-here");
},
type: "POST",
// Request body
data: '{"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"}',
})
.done(function(data) {
alert("success");
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
</body>
</head>
</html>
This may seem like stupid question however I've been wondering how to get the emotions output from the HTML file? i.e. instead of the success alert I'd like to generate a text file which shows the output of the Emotions API with each emotion (like it does on their website).
One solution could be to read about Blob's. You could take the response from the ajax call in done() and create the text file you need. Here is an example for using Blob I found on JSFiddle:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
source
data is an array, one item per face. If you just want to dump the text, you can call JSON.stringify(data). If you want pretty-print it in HTML, take a look at How can I pretty-print JSON using JavaScript?.
I've done this ins my website HowHappy.co.uk which is also on GitHub here: https://github.com/martinkearn/How-Happy
The way I displayed the data in a web site was to enumerate the array of faces in Javascript and use basic CSS to show the rectangle in the right place and Bootstrap popover to show the details data.
There is too much to put in this response so I recommend you look though the GitHub repo, but here are some of the key bits
Javascript
var dataString = JSON.stringify(response);
var data = JSON.parse(dataString);
//draw rectangle for each face
$.each(data.Faces, function (index, value) {
var rect = document.createElement('div');
rect.className = "rect";
rect.style.height = value.faceRectangle.height + "px";
rect.style.width = value.faceRectangle.width + "px";
rect.style.left = value.faceRectangle.left + "px";
rect.style.top = value.faceRectangle.top + "px";
rect.id = "rect" + index;
$('#result').append(rect);
//add popover
var popoverBody = "Happiness: " + Number((value.scores.happiness).toFixed(2))
+ "<br>Fear: " + Number((value.scores.fear).toFixed(2))
+ "<br>Anger: " + Number((value.scores.anger).toFixed(2))
+ "<br>Contempt: " + Number((value.scores.contempt).toFixed(2))
+ "<br>Disgust: " + Number((value.scores.disgust).toFixed(2))
+ "<br>Neutral: " + Number((value.scores.neutral).toFixed(2))
+ "<br>Sadness: " + Number((value.scores.sadness).toFixed(2))
+ "<br>Surprise: " + Number((value.scores.surprise).toFixed(2));
$('#rect' + index).popover({
title: (index + 1)
content: popoverBody,
html: "true",
trigger: "click"
});
});
Css
.rect {
position: absolute;
border-color: #FFEA0E;
border-style: solid;
border-width: 4px;
z-index: 10;
}
#result {
position: relative;
text-align: center;
margin: 0 auto;
width: auto;
}
#resultDetails {
font-size: 3rem;
text-align: center;
}

SpreadJS ClipboardPasteOptions is set to "All" but no formatting is applied

i open a spreadsheet and i can see in console:
_clipBoardOptions: "All"
in activeSheet obj.
but whenever i try to paste formatting from excel it just passes the value.
any thoughts on were i'm going wrong.?
Basically the default is "All" but no formatting is passed to SpreadJS
Here's my initialisation
$("#ss").wijspread({sheetCount:1}); // create wijspread control
var spread = $("#ss").wijspread("spread"); // get instance of wijspread control
var sheet = spread.getActiveSheet();
also when i try manually adding the method after the initialisation as so :
sheet.clipBoardOptions($.wijmo.wijspread.ClipboardPasteOptions[0])
i tried looking for a solution but not much information is giving and the api is kinda bum !
thanks in advance to any of you helpers!
SpreadJS does not support pasting formatting from Excel. We are looking into ways that we can implement support for that in a future release.
For now, SpreadJS can only import the entire Excel workbook using the ExcelIO web service.
To get the content of a cell range copied to SpreadJS, the best suggestion I have now is to use ExcelIO to import that workbook to a hidden SpreadJS instance, then use ClipboardPasteUndoAction to copy and paste the range from the hidden SpreadJS to the visible one.
Here is a code example showing how to use the ExcelIO web service to import an Excel file:
<!DOCTYPE html>
<html>
<head>
<title>Excel IO Sample</title>
<link type="text/css" href="./css/cobalt/jquery-wijmo.css" rel="stylesheet" />
<link type="text/css" href="./css/gcspread.sheets.8.40.20151.0.css" rel="stylesheet" />
<script type="text/javascript" src="./external/jquery-1.9.1.js"></script>
<script type="text/javascript" src="./scripts/gcspread.sheets.all.8.40.20151.0.min.js"></script>
<script type="text/javascript">
$(function () {
//Initialize SpreadJS
new GcSpread.Sheets.Spread($("#ss").get(0), {sheetCount: 2});
//For Excel Import
$("#btn_Import").click(function () {
// SpreadJS Excel IO import service api.
var serverUrl = $("#serviceHost").val() + "/xsapi/import";
// Generate import api options
var formData = new FormData();
//Choose a file to import
var $importingFile = $("#loadExcel");
var theFile = $importingFile[0].files[0];
var accept = "application/json";
formData.append("file", theFile);
formData.append("ExcelOpenFlags", "NoFlagsSet");
formData.append("TextFileOpenFlags", "None");
formData.append("Password", "");
$.ajax({
//Server script to process data
url: serverUrl,
type: 'POST',
//Ajax events
success: function completeHandler(data, textStatus, jqXHR) {
var spread = $("#ss").data("spread");
spread.fromJSON(JSON.parse(jqXHR.responseText).spread);
},
error: function errorHandler(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
//Options to tell server return data with specified type
headers: {
"Accept": accept
}
});
});
//For Excel Export with Form Post.
$("#btn_Export").click(function () {
var spread = $("#ss").data("spread");
// SpreadJS Excel IO import service api.
var serverUrl = $("#serviceHost").val() + "/xsapi/export";
// Generate import api options
var optContentType = "application/json";
// Post the json from spreadjs.
var dataObj = {
"spread": spread.toJSON(),
"exportFileType": "xlsx",
"excel": {
"saveFlags": "NoFlagsSet",
"password": ""
},
};
var content = JSON.stringify(dataObj);
var formInnerHtml = '<input type="hidden" name="type" value="' + htmlSpecialCharsEntityEncode(optContentType) + '" />';
formInnerHtml += '<input type="hidden" name="data" value="' + htmlSpecialCharsEntityEncode(content) + '" />';
var $iframe = $("<iframe style='display: none' src='about:blank'></iframe>").appendTo("body");
$iframe.ready(function () {
var formDoc = getiframeDocument($iframe);
formDoc.write("<html><head></head><body><form method='Post' action='" + serverUrl + "'>" + formInnerHtml + "</form>dummy windows for postback</body></html>");
var $form = $(formDoc).find('form');
$form.submit();
});
});
});
//gets an iframes document in a cross browser compatible manner
function getiframeDocument($iframe) {
var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframeDoc.document) {
iframeDoc = iframeDoc.document;
}
return iframeDoc;
}
var htmlSpecialCharsRegEx = /[<>&\r\n"']/gm;
var htmlSpecialCharsPlaceHolders = {
'<': 'lt;',
'>': 'gt;',
'&': 'amp;',
'\r': "#13;",
'\n': "#10;",
'"': 'quot;',
"'": 'apos;' /*single quotes just to be safe*/
};
function htmlSpecialCharsEntityEncode(str) {
return str.replace(htmlSpecialCharsRegEx, function (match) {
return '&' + htmlSpecialCharsPlaceHolders[match];
});
}
</script>
</head>
<body>
<h2>SpreadJS Excel IO Sample</h2>
<div style="margin-bottom: 10px">
<label><b>Excel IO Service Host : </b></label>
<input id="serviceHost" value="http://localhost/ExcelIO" style="width: 500px" />
</div>
<div id="ss" style="width: 660px; height: 500px; border: 1px solid gray; float: left">
</div>
<div style="width: 30%; height: 500px; margin-left: 15px; float: left">
<fieldset style="margin-bottom: 15px; height: 45%">
<legend><b>Excel IO Import Options</b></legend>
<input type="file" id="loadExcel" accept=".xlsx, .xls, .csv, .txt" />
<input id="btn_Import" type="button" value="Import" />
</fieldset>
<fieldset style="margin-bottom: 15px; height: 45%">
<legend><b>Excel IO Export Options</b></legend>
<input id="btn_Export" type="button" value="Export" />
</fieldset>
</div>
</body>
</html>
link: http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#exceliocode.html
Here is a code example showing how to use the ClipboardPasteUndoAction:
$(document).ready(function () {
//There are two buttons in html page with the id "cutPasteBtn" and "copyPasteBtn".
var spread = new GcSpread.Sheets.Spread($("#ss").get(0),{sheetCount:3});
var sheet = spread.getActiveSheet();
sheet.setValue(0, 0, 1, GcSpread.Sheets.SheetArea.viewport);
sheet.setValue(1, 0, 2, GcSpread.Sheets.SheetArea.viewport);
sheet.setFormula(2, 0, "=A1+A2", GcSpread.Sheets.SheetArea.viewport);
sheet.setValue(0, 1, 3, GcSpread.Sheets.SheetArea.viewport);
sheet.setValue(1, 1, 4, GcSpread.Sheets.SheetArea.viewport);
sheet.setFormula(2, 1, "=B1+B2", GcSpread.Sheets.SheetArea.viewport);
var fromRange = new GcSpread.Sheets.Range(0, 0, 3, 2);
var toRanges = [new GcSpread.Sheets.Range(4, 0, 3, 2)];
$("#cutPasteBtn").click(function () {
//Cut Paste Action
var clipboardCutPasteAction = new GcSpread.Sheets.UndoRedo.ClipboardPasteUndoAction(sheet, sheet, sheet, { fromRange: fromRange, pastedRanges: toRanges, isCutting: true, clipboardText: "" }, GcSpread.Sheets.ClipboardPasteOptions.Values);
clipboardCutPasteAction.execute(sheet);
});
$("#copyPasteBtn").click(function () {
//Copy Paste Action
var clipboardCopyPasteAction = new GcSpread.Sheets.UndoRedo.ClipboardPasteUndoAction(sheet, sheet, sheet, { fromRange: fromRange, pastedRanges: toRanges, isCutting: false, clipboardText: "" }, GcSpread.Sheets.ClipboardPasteOptions.Values);
clipboardCopyPasteAction.execute(sheet);
});
});
link: http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#sccopy.html
Regards,
GrapeCity Experts

dom is undefined error when trying to upload shapefile

I have been working on an arcgis project for the last two weeks and I have ran into an issue with my upload shapefile function in my code. I keep getting an dom is undefined error and I don't know what to do.
Here is the code:
<div class="modal fade" id="UpdateShapefileForm" tabindex="-1" role="dialog" aria- labelledby="Set View" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<form enctype="multipart/form-data" method="post" id="uploadForm">
<div class="field">
<label class="file-upload">
<span><strong>Add File</strong></span>
<input type="file" name="file" id="inFile"/>
</label>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="http://js.arcgis.com/3.9/"></script>
<script src="/static/js/mapping/mapobject.js" type="text/javascript"></script>
<script src="/static/js/mapping/mapmanager.js" type="text/javascript"></script>
<script type="text/javascript">
var map, toolbar;
var PROJECT_OUTLINE, PROJECT_FILL, PARCEL_OUTLINE, PARCEL_FILL, PLOT_OUTLINE, PLOT_FILL;
var toolbarEvent;
var mapManager = new MapManager();
var markerPictures = {
'project': '/static/assets/grnball.png',
'parcel': '/static/assets/bluball.png',
'plot': '/static/assets/redball.png'
}
require([
"esri/config",
"esri/InfoTemplate",
"esri/map",
"esri/request",
"esri/geometry/scaleUtils",
"esri/layers/FeatureLayer",
"esri/renderers/SimpleRenderer",
"esri/symbols/PictureMarkerSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/SimpleLineSymbol",
"esri/symbols/SimpleMarkerSymbol",
"dojo/dom",
"dojo/json",
"dojo/on",
"dojo/parser",
"dojo/sniff",
"dojo/_base/array",
"esri/Color",
"dojo/_base/lang",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dojo/domReady!"
], function(
esriConfig, InfoTemplate, Map, request, scaleUtils, FeatureLayer,
SimpleRenderer, PictureMarkerSymbol, SimpleFillSymbol, SimpleLineSymbol, SimpleMarkerSymbol,
dom, JSON, on, parser, sniff, arrayUtils, Color, lang
) {
map = new Map("mapcanvas", {
center: [-56.049, 38.485],
zoom: 3,
basemap: "hybrid"
});
map.on("load", function() {
$("#waiting_img").hide();
createToolbar();
setConstants();
parser.parse();
var portalUrl = "http://www.arcgis.com";
esriConfig.defaults.io.proxyUrl = "/proxy";
on(dom.byId("uploadForm"), "change", function (event) {
var fileName = event.target.value.toLowerCase();
if (sniff("ie")) { //filename is full path in IE so extract the file name
var arr = fileName.split("\\");
fileName = arr[arr.length - 1];
}
if (fileName.indexOf(".zip") !== -1) {//is file a zip - if not notify user
generateFeatureCollection(fileName);
}
else {
dom.byId('upload-status').innerHTML = '<p style="color:red">Add shapefile as .zip file</p>';
}
map.graphics.on("click", function(evt) {
console.log("geometry type: " + evt.graphic.geometry.type);
if(evt.graphic.geometry.type == "polygon")
{
selectPolygon();
}
else if(evt.graphic.geometry.type == "multipoint" || evt.graphic.geometry.type == "point")
{
selectMarker();
}
});
});
});
});
function generateFeatureCollection (fileName) {
var name = fileName.split(".");
//Chrome and IE add c:\fakepath to the value - we need to remove it
//See this link for more info: http://davidwalsh.name/fakepath
name = name[0].replace("c:\\fakepath\\", "");
dom.byId('upload-status').innerHTML = '<b>Loading </b>' + name;
//Define the input params for generate see the rest doc for details
//http://www.arcgis.com/apidocs/rest/index.html?generate.html
var params = {
'name': name,
'targetSR': map.spatialReference,
'maxRecordCount': 1000,
'enforceInputFileSizeLimit': true,
'enforceOutputJsonSizeLimit': true
};
//generalize features for display Here we generalize at 1:40,000 which is approx 10 meters
//This should work well when using web mercator.
var extent = scaleUtils.getExtentForScale(map, 40000);
var resolution = extent.getWidth() / map.width;
params.generalize = true;
params.maxAllowableOffset = resolution;
params.reducePrecision = true;
params.numberOfDigitsAfterDecimal = 0;
var myContent = {
'filetype': 'shapefile',
'publishParameters': JSON.stringify(params),
'f': 'json',
'callback.html': 'textarea'
};
//use the rest generate operation to generate a feature collection from the zipped shapefile
request({
url: portalUrl + '/sharing/rest/content/features/generate',
content: myContent,
form: dom.byId('uploadForm'),
handleAs: 'json',
load: lang.hitch(this, function (response) {
if (response.error) {
errorHandler(response.error);
return;
}
var layerName = response.featureCollection.layers[0].layerDefinition.name;
dom.byId('upload-status').innerHTML = '<b>Loaded: </b>' + layerName;
addShapefileToMap(response.featureCollection);
}),
error: lang.hitch(this, errorHandler)
});
}
function errorHandler (error) {
dom.byId('upload-status').innerHTML =
"<p style='color:red'>" + error.message + "</p>";
}
function addShapefileToMap (featureCollection) {
//add the shapefile to the map and zoom to the feature collection extent
//If you want to persist the feature collection when you reload browser you could store the collection in
//local storage by serializing the layer using featureLayer.toJson() see the 'Feature Collection in Local Storage' sample
//for an example of how to work with local storage.
var fullExtent;
var layers = [];
arrayUtils.forEach(featureCollection.layers, function (layer) {
var infoTemplate = new InfoTemplate("Details", "${*}");
var featureLayer = new FeatureLayer(layer, {
infoTemplate: infoTemplate
});
//associate the feature with the popup on click to enable highlight and zoom to
featureLayer.on('click', function (event) {
map.infoWindow.setFeatures([event.graphic]);
});
//change default symbol if desired. Comment this out and the layer will draw with the default symbology
fullExtent = fullExtent ?
fullExtent.union(featureLayer.fullExtent) : featureLayer.fullExtent;
layers.push(featureLayer);
});
map.addLayers(layers);
map.setExtent(fullExtent.expand(1.25), true);
dom.byId('upload-status').innerHTML = "";
}
function setConstants() {
PROJECT_OUTLINE = new esri.Color(([0,255,0]));
PROJECT_FILL = new esri.Color([0,255,0,0.5]);
PARCEL_OUTLINE = new esri.Color(([0,0,255]));
PARCEL_FILL = new esri.Color([0,0,255,0.5]);
PLOT_OUTLINE = new esri.Color(([255,0,0]));
PLOT_FILL = new esri.Color([255,0,0,0.5]);
}
function createToolbar() {
toolbar = new esri.toolbars.Draw(map);
}
function drawEnd(geometry, pType, outline, fill) {
toolbar.deactivate();
map.showZoomSlider();
console.log("geometry: " + geometry.type);
var text_symbol = null;
switch (geometry.type) {
case "point":
case "multipoint":
symbol = new esri.symbol.PictureMarkerSymbol(markerPictures[pType], 13, 13);
break;
default:
symbol = new esri.symbol.SimpleFillSymbol();
symbol.setColor(fill);
symbol.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, outline, 2));
break;
}
var graphic = new esri.Graphic(geometry, symbol);
map.graphics.add(graphic);
var map_obj = new MapObject(pType, pType, graphic, geometry.type);
mapManager.Add(map_obj);
if(toolbarEvent != null)
{
toolbarEvent.remove();
toolbarEvent = null;
}
}
error happens specifically on this line:
dom.byId('upload-status').innerHTML = '<b>Loading </b>' + name;
You've got a simple scoping error - the variable dom is declared as an argument to this function:
require([...,"dojo/dom",...], function(...,dom,...) {...});
Your next function declaration is this:
function generateFeatureCollection (fileName) {
...
dom.byId(...);
...
}
but the variable dom is not defined in this function, so you can't use it here. You need to either pass it to the function:
function generateFeatureCollection (fileName, dom) {...}
which gets very clumsy if you're going to pass it around to every function, assign the dom variable in your require function to a global variable, or redeclare it where you need it. From the docs:
require(["dojo/dom"], function(dom){
// fetch a node by id="someNode"
var node = dom.byId("someNode");
});

Passing values between two javascript in a html

I have a case where i need to load a char based on the input from another javascript. But it doesn't work in my case. I have added the code below:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart', 'table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var json = $.ajax({
url: fileURL, // make this url point to the data file
dataType: 'json',
cahce:false,
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title: graphTitle,
is3D: 'true',
width: 800,
height: 600
};
var tableOptions = {
title: 'App Listing'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
and I pass the value for graphtitle and fileURL as below:
<script type="text/javascript">
$(document).ready(function () {
var fileURL = "";
var graphTitle = "";
function showDiv() {
if($firstCheck) {
var selText;
$("#dd4 li a").show(function () {
selText = $(this).text();
});
if(selText !== "Factor"){
if(selText == "IA Architecture Usage"){
fileURL = "get_json.php";
graphTitle = "IA Architecture Variation";
}else if(selText == "Tablet to Phone"){
fileURL = "get_tablet_support.php";
graphTitle = "Tablet Usage Variation";
}
document.getElementById('chart_div').style.display = "block";
}
}else{
document.getElementById('chart_div').style.display = "none";
}
}
</script>
Both these javascript are within the same file. I can't pass the fileURL and graphTitle when I used the above code. Any idea how to solve this issue?
Use global variables with window. E.g.
$(document).ready(function () {
window.fileURL = "";
window.graphTitle = "";
});
Don't specify "var" or it will only be within the scope of the function.
EDIT: Also make sure that the script in which your variables are assigned initially is before the other one.
How about something a bit more OO oriented (not really OO, but less inline code) ? It's cleaner and easier to read/maintain ..example could still use some work, but i"m sure you get the idea.
function loadChart(title, url) {
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart', 'table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var json = $.ajax({
url : url, // make this url point to the data file
dataType: 'json',
cahce : false,
async : false
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title : title,
is3D : 'true',
width : 800,
height: 600
};
var tableOptions = {
title: 'App Listing'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
$(document).ready(function () {
var fileURL = "";
var graphTitle = "";
function showDiv() {
if($firstCheck) {
var selText;
$("#dd4 li a").show(function () {
selText = $(this).text();
});
if(selText !== "Factor") {
if(selText == "IA Architecture Usage"){
fileURL = "get_json.php";
graphTitle = "IA Architecture Variation";
} else if(selText == "Tablet to Phone"){
fileURL = "get_tablet_support.php";
graphTitle = "Tablet Usage Variation";
}
document.getElementById('chart_div').style.display = "block";
}
} else {
document.getElementById('chart_div').style.display = "none";
}
loadChart(graphTitle, fileURL);
}
}
btw i think you have an error in your code: .responseText seems pretty useless to me, and most likely throws an error in itself. Also i have no idea who is calling showDiv() in the code. From the example, i'd say it never fires.

Categories

Resources