Javascript data structure - javascript

I have a script that I'm working on, this script reads a zip file and extracts the contents of the files inside the zip. What I'm trying to do is send a request to my server in the following format:
file0name,contentfile0;file1name,contentfile1;file2name,contentfile2
Can someone tell me what type of data structure I should use? Is it a list or a JSON object?
https://jsfiddle.net/ker1w6pb/6/

Assuming you convert your content into a string (which sounds odd to me), you can just POST a JSON data object containing your string:
var postData = [{
filename: 'file0',
content: 'content0'
}, {
filename: 'file1',
content: 'content1'
}, {
filename: 'file2',
content: 'content2'
}];
var postString = postData.reduce(function(previous, current) {
return previous + current.filename + ',' + current.content + ';';
}, '');
//post(uri, {data: postString});
document.write(postString);

Related

Using ajax call to generate array for link_list for tinymce

I'm trying to create a link_list in TinyMCE (version 6) using an AJAX call (not sure if this is the right way, but I'm trying to update old code). The backend is handled with Flask, which gets a tuple of dictionaries from the database where the title and value of each link are key-value pairs. I believe what I need to do is find a way to make the ajax call return the correct type of array, e.g.
my_ary=[
{ title: 'title 1',value: 'link1'},
{ title: 'title 2',value: 'link2'},
{ title: 'title 3',value: 'link3'},
]
Is this possible? Or am I heading in a completely incorrect direction? This is what I currently have-
tinyMCE intialization:
tinymce.init({
selector: '.my_editor',
plugins: ['link'],
toolbar: 'link',
link_list: (success) => {
const links = update_item_list();
success(links);
},
});
javascript containing ajax call:
function update_item_list()
{
my_link_list = $.ajax({
async: false,
type: "POST",
url: "ajax_endpoint",
data: {},
cache: false,
dataType: "json",
success: function(list)
{
const my_ary=Array.from(Array(list.length), () => ({ title: '', value: '' }))
for(var i = 0; i < list.length; i++)
{
my_ary[i].title=list[i].title;
my_ary[i].value=list[i].value;
}
},
error: function(html, status)
{
alert("error: " + status);
}
});
return my_link_list;
}
flask endpoint:
#my_project.route('/ajax_endpoint',methods=['POST'])
def ajax_endpoint():
uploaded_items = ["{" + ", ".join([f"""'{key}': '{item.get(key)}'""" for key in item.keys()]) + "}" for item in get_link_items()]
html = "[" + ", ".join(uploaded_items) + "]"
return jsonify(html)
I figured out a solution without using ajax. Per tinyMCE's documentation for link_list, one can use a URL which returns JSON data. To accomplish this, I created a list of dictionaries with keys of "title" and "value" for each link, and then used jsonify when returning the list. Now, this is what my code looks like-
tinyMCE intialization:
tinymce.init({
selector: '.my_editor',
plugins: ['link'],
toolbar: 'link',
link_list: "ajax_endpoint"
},
});
flask endpoint:
#my_project.route('/ajax_endpoint',methods=['POST'])
def ajax_endpoint():
html = [{"title": item.get('title'), "value": item.get('value')} for item in get_link_items()]
return jsonify(html)

Parsing JSON-like file type to JSON in JavaScript

I have lots of files with an unusual file extension.
I need to read the files using JavaScript and convert their contents to JSON or regular JavaScript objects.
Is this even possible?
I have some hope, because the files are already structured very similar to JSON:
// file.unusualFileType
Page: {
id: P001
Title: "Page Title"
URL: "/home"
Elements: {
Button: {
Text: "Click me"
Action: SAVE
}
}
}
EDIT: HÃ¥ken Lid kindly provided a solution for my particular use case. Out of curiosity I would still be interested in how to read any file as a string with JavaScript and how one could possible parse such a string.
It would be valid yaml if you strip out the curly brackets. You can use js-yaml to parse the sample data, so maybe it works with the rest of your files too?
const rawData = `
Page: {
id: P001
Title: "Page Title"
URL: "/home"
Elements: {
Button: {
Text: "Click me"
Action: SAVE
}
}
}`
const yamlData = rawData.replace(/[{}]/g, '')
console.log(jsyaml.load(yamlData))
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.13.1/js-yaml.min.js"></script>

How can I save or update to a file after adding a new object to it?

I'm trying to update/save a js file after a forum submission.
My application is an electron / react desktop app. I have a bunch of objects saved in a .js file each object represents a help file.
HelpData.js looks similar to this.
const HelpData = [
{
name: '',
menu: '',
content: ''
},
{
name: '',
menu: '',
content: ''
},
]
export default HelpData;
My component loads in the data found in this file and pushes a new object into the array of objects. Everything works fine when the application is running, but when you exit the application the new file that was added is lost.
I need to figure out a way to save the file added to HelpData.js
Here is the function that adds the file to array of object:
handleSubmit(e) {
e.preventDefault();
let newFile = { name: '', menu: '', title: '', path: '', content: '', section: 'Section IV', video: 'n' }
newFile.name = this.state.name;
newFile.menu = this.state.menu;
newFile.title = this.state.title;
newFile.path = this.state.path;
newFile.content = this.state.content;
HelpData.(newFile);
// now that the new file has been pushed onto HelpData array, I need to save the file HelpData.js. This is what I'm not sure how to do in javascript.
}
After I push the new file into the HelpData array, how can I either rewrite HelpData.js and save the file, or write directly into the file and save?

Is it possible to update js file using php command?

I have script.js file. and it has following array
script.js
'COntent': function() {
var contentFacts = {
blocks: {
'block1': {
name: 'yleow',
title: 'H2',
type: 'content'
}
}
};
}
},
I tried like this in my php , but it did not work :(
$lines = file($path.'/script.js');
$lines[64] = "'block2': {name: 'yleow',title: 'H2',type: 'content'}"
file_put_contents($path.'/script.js', implode($lines));
I want to add another element call block2 for this array. How can i update my script.js file function using php?
Is it possible using file_put_contents? please advice
JavaScript is a very poor substitute for a database or any other structured data format. In this case even more because you are trying to inject content into source code.
What you probably want is some form of structured data outside of your code for example a JSON file or an SQLite database.
PHP does support parsing from and serializing to JSON:
json_decode
json_encode
Possible solution
Put the contentFacts into a seperate JSON file
{
"blocks": {
"block1": {
name: 'yleow',
title: 'H2',
type: 'content'
}
}
}
Manipulate JSON with PHP
$json = file($path.'/blocks.json');
$blocks = json_decode($json, true);
$blocks['block2'] = array(
'name' => 'blue',
'title' => 'h3',
'type' => 'content'
);
Write back to JSON file
$adapted_json = json_encode($blocks);
file_put_contents($path.'/blocks.json');
Now you need to get this into your JavaScript part, I assume on the client. You can do this by requesting it from the server:
const contentPromise = fetch('/path/to/blocks.json');
contentPromise.then((blocks) => {
// Do something with those blocks. (render them to the page?)
});

Angular how to compile whole jTable after dynamic load from server

I am using .NET to assemble some of the fields on the server for jTable. My problem is how to compile changed table after load, so angular events are compiled to $scope. What I've tried is to compile the whole html body, but it doesn't work. Nothing happens. What should I do? Some fields must be assembled on the server. Why is $compile($("body"))($scope) not compiling whole body?
My thinking is that whatever element is added to DOM, if I compile the whole documents body, all angular events should be binded to $scope.
Here is the function on the server (ng-blur event is added to the input field inputQuantity):
public JsonResult GetListFromIACC_KEY(int jtStartIndex, int jtPageSize, string orderBy)
{
List<DTO_CAMERC> listResults = new List<DTO_CAMERC>();
x.Quantity = SetTextBoxFieldInJTable(value: x.Quantity,
attribute1: #"id='inputQuantity'",
attribute2: #"ng-blur='alert();'");
return x;
}).OrderBy(x => x.iMERC_KEY).ToList();
}
return Json(new { Result = "OK", Records = listResults, TotalRecordCount = listResults.Count });
}
Function for creating input field:
private string SetTextBoxFieldInJTable(string value = null, string attribute1 = null, string attribute2 = null)
{
return #"<input type='text' class='cellContent'" +
"value='" + value + #"' " + attribute1 + " " +
attribute2 + ">";
}
Client call (here I've tried to compile whole html body after jTable has loaded, but id doesn't work - nothing happens when field inputQuantity loses focus):
$http({
method: "POST",
url: $scope.UrlSetIACCO_KEY,
data: JSON.stringify(model)
}).then(function success(response) {
jQuery('#tblDeliveryList').jtable('load');
//Here I try to compile the whole body, after the jTable has loaded,
//but ng-blur is not working
$compile($("body"))($scope);
}, function failure() {
alert("Napaka!");
})
});
Table on the client:
jQuery('#tblDeliveryList').jtable({
title: 'Delivery',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'cMERC_NME ASC',
actions: {
listAction: $scope.UrlGetDataFromIACCO_KEY
},
Quantity: {
title: 'Quantity',
width: '3%',
sorting: false
}
})
You are doing the compile wrong. $('body') returns a jQuery object. What you need to do is to return HTML dom object for angular to compile. Also, compiling the jTable html alone is enough. Try the following:
$compile(document.getElementById('tblDeliveryList'))($scope);

Categories

Resources