Please I need help on accessing data in a CSV file that is stored locally on my app.
What I want to do is when a user clicks the search input on the app, it should display data from the locally stored CSV file.
I tried the popular root but it can only access a .js file, I need one that can read a CSV file.
Please help!!
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script
>
Use the FileReader API to access a local CSV file:
function readCSV()
{
var fileString = arguments[0].target.result;
return fileString
}
with (new FileReader)
{
var files = document.getElementById('files').files[0];
onloadend = readCSV;
readAsText(files, "utf-8");
}
Related
I'm trying to create a file in the File Cabinet and write to it in a Client Script. Checking the API reference, I see that all the File objects are Server-side only.
Does that mean you can't create and write to a file in a Client script? I tried to use the code in my Client script anyway, but got the error:
Fail to evaluate script: {"type":"error.SuiteScriptModuleLoaderError","name":"{stack=[Ljava.lang.Object;#59c89ae9, toJSON=org.mozilla.javascript.InterpretedFunction#5a4dd71f, name=MODULE_DOES_NOT_EXIST, toString=org.mozilla.javascript.InterpretedFunction#1818dc3c, id=, message=Module does not exist: N/file.js, TYPE=error.SuiteScriptModuleLoaderError}","message":"","stack":[]}
When I tried to save it in NetSuite as the script file. Does the above mean that the N/File object can't be loaded in a Client script?
Can I write to a file in a Client script?
Create a Client Script - this Script will contain the function to call the Suitelet and pass along information from the current record/session if needed.
function pageInit{
//required but can be empty
}
function CallforSuitelet(){
var record = currentRecord.get();
var recId = record.id;
var recType = record.type
var suiteletURL = url.resolveScript({
scriptId:'customscriptcase3783737_suitelet',// script ID of your Suitelet
deploymentId: 'customdeploycase3783737_suitelet_dep',//deployment ID of your Suitelet
params: {
'recId':recId,
'recType':recType
}
});
document.location=suiteletURL;
}
return {
CallforSuitelet : CallforSuitelet,
pageInit : pageInit
}
Create a Suitelet - this script will create the file
function onRequest(context) {
var requestparam = context.request.parameters;
var recId = requestparam.recId; //the same name of the fields specified in url.resolveScript parameters from Client Script
var recType = requestparam.recType;
var objRecord = record.load({
type: record.Type.___,//insert record type
id: recId
});
var content = 'Insert Content Here';
var xml = "<?xml version=\"1.0\"?>\n<!DOCTYPE pdf PUBLIC \"-//big.faceless.org//report\" \"report-1.1.dtd\">\n";
xml += "<pdf>\n<body font-size=\"12\">\n<h3>Sample PDF</h3>\n";
xml += "<p></p>";
xml += content;
xml += "</body>\n</pdf>";
context.response.renderPdf({xmlString: xml});
}
return {
onRequest: onRequest
}
As you've already discovered, server-only modules can't be called from client-side scripts directly, but this can be done via a Suitelet. You will need to decide how the Suitelet does it's work. An example of the principal at work can be found here and here
My current script uses the code below to download a CSV file to local drive,
function table2CSV() {
var dataURL = '',
fieldSeparator = ',',
textField = '"',
lineSeparator = '\n',
regExpTesto = /(")/g,
regExp = /[";]/;
$('table tr').each(function() {
var dataRow = '';
if ($('input:checkbox', this).is(':checked') || $(this).is(':first- child'))
{
$('td', this).not(':last').each(function() {
var value = $(this).text();
if (dataRow !== '') dataRow += fieldSeparator;
if (regExp.test(value)) {
value = textField + value.replace(regExpTesto, '$1$1') + textField;
}
dataRow += value;
});
if (dataURL !== '') dataURL += lineSeparator;
dataURL += dataRow;
}
});
window.location.href = 'data:text/csv;charset=utf-8;base64,' + btoa(dataURL);
}
The download is done bye this line as far as I can tell :
window.location.href = 'data:text/csv;charset=utf-8;base64,' + btoa(dataURL);
I would like to be able to have it download(upload/saved) to a shared google drive folder instead.
I have seen similar questions on the forum but can't seem to see how to point the download to a shared google-drive folder.
What must code must be added/changed in order to achieve this ?
Thank you
EDIT: Nevermind, just realised they say it does not support data URIs:
Data URIs and file:// URLs are not supported
I will keep this answer in case anyone else searches for non-data URI uploading
Having a quick look, I came upon Save to Drive
While this might not be exactly what you want, it looks like an easy way to add the ability to save the contents of any URI (hopefully a data URI too) to Google Drive, like so:
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="g-savetodrive"
data-src="//example.com/path/to/myfile.pdf"
data-filename="My Statement.pdf"
data-sitename="My Company Name">
</div>
I have one file i.e style.css/any file whose content need to be shifted to another text file which is file.txt. Using ActiveXObject is not working, so could you please provide any other solution.?
Here is my code which I tried.
jQuery(function ($) {
$.get('css/style.css', function (data) {
// alert(data);
writeToFile(data);
});
function writeToFile(content) {
// alert(content);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("file.txt", 8);
fh.WriteLine(content);
fh.Close();
}
});
You can try this
window.location = "data:text/html," + yourData
It'll dump the data in the url and force a download of the data.
i am getting json data from a files and create another json files in each loop and send request for that json files here is my code for creating json files
var derivatedFeatures = ["RMS","sb2xMagnitudev_ipspeak", "sbSubsynchronousv_ipspeak", "PeakPeak_mil", "sbHighFrequency_grms", "TruePeak_ips", "PeakPeak_g", "sb1xMagnitudev_ipspeak","Crestfactor"];
$.each(derivatedFeatures,function(index,feature){
$.each(data,function(index,item){
var featurefile ="Lines_"+feature+'_'+item['Line']+'_'+item['Component'].split(" ").join("_")+'.json'
filedata = {
file:featurefile,
site:item['Site'],
area:item['Area'],
line:item['Line'],
equipment:item['Equipment'],
component:item['Component'],
feature:feature
};
frank.sendAjax('/static/data/json/'+featurefile,'', 'GET', anomaliesDataAppend,filedata);
});
});
i want to load 10 files first
after page scroll i want to load 10 more
and processes continue
Reason for doing this
page stuck while loading all of json files and processing its data
i have 2000+ json files
i hope this help you:
here is i coded for your solution
$.each(derivatedFeatures,function(index,feature){
$.each(data,function(index,item){
indexnum++;
var featurefile ="Lines_"+feature+'_'+item['Line']+'_'+item['Component'].split(" ").join("_")+'.json'
filedata.push({file:featurefile,
site:item['Site'],
area:item['Area'],
line:item['Line'],
equipment:item['Equipment'],
component:item['Component'],
feature:feature,
indexnum:indexnum
});
});
});
loadFeatureFiles(filedata,0);
var loadFeatureFiles = function(filedata,indexnum){
var startfrom=indexnum;
var endto=startfrom+10;
for (var i=startfrom;i <= endto;i++) {
requestdata={filedata:filedata[i],indexnum:i};
frank.sendAjax('/static/data/json/'+filedata[i]['file'],'', 'GET', anomaliesDataAppend,requestdata);
};
};
assign data= rows and get when user scroll down and pass in the function
//data is induxnum
loadFeatureFiles(filedata,data);
I wanna add new Object that containing an Image in one of its columns , but it dose not save My Pic , Is there any mistake in my code ? specially part of saving Image !!
My JavaScript where the problem appeared:
It never upload my pic in parse !!
<script type="text/javascript">
Parse.initialize("key", "key");
var products = Parse.Object.extend("products");
var fileUploadControl = $("#profilePhotoFileUpload")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
}
parseFile.save().then(function() {
//The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
</script>
Here I added html line to upload file:
<input type="file" id="profilePhotoFileUpload">
I got the answer I am sharing it with you maybe someone get benefit
The THML line to upload file is:
<input type="file" id="pic">
The code in <script> to get and save image in parse is :
var fileUploadControl = $("#pic")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
//put this inside if {
parseFile.save().then(function() {
// The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
// Be sure of ur parameters name
// prod is extend of my class in parse from this: var prod = new products();
prod.set("picture", parseFile);
prod.save();
}
Check the documentation here (at the end of that section, just before the one about retrieving files). Basically the issue is that like any other Parse object you need to save it first, then after the save is complete you can use it.
Create the file, save it, and in the save success handler you can then save the object with the reference to the file.
UPDATE: here's how your code above could be fixed:
Parse.initialize("key", "key");
var products = Parse.Object.extend("products");
var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
var file = new Parse.File("mypic.png", { base64: base64 });
file.save({
success: function(file) {
alert('File saved, now saving product with file reference...');
var prod = new products();
// to fill the columns
prod.set("productID", 1337);
prod.set("price", 10);
//I guess it need some fixing here
prod.set("picture", file);
prod.set("productName", "shampoo");
prod.set("productDescribe", "200 ml");
prod.save(null, {
success: function(prod) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + prod.id);
},
error: function(error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
},
error: function(error) {
alert('Failed to save file: ' + error.description);
}
});