Load json from text file - javascript

I have the following hard coded json,
var dataLocality = [
{ "label": "Arwen" },
{ "label": "Bilbo Baggins" },
{ "label": "Boromir" },
{ "label": "Frodo Baggins" },
{ "label": "Peregrin Pippin Took" },
{ "label": "Samwise Gamgee" }
];
Which I use to populate an autocomplete textbox with the following script,
$(function () {
$("#locality").autocomplete(
{
source: dataLocality
})
});
I now have a text file that is dynamically updated via my app named dataLocality.text which i'm able to load and view in an alert box with this code,
function codeAddress() {
jQuery.get('http://localhost/project/jSonDocs/dataWhat.txt', function (data) {
var dataLocality = data;
alert(dataLocality);
});
}
window.onload = codeAddress;
But I can't seem to work out how to get the data from var dataLocality to source: dataLocality
The data in my text doc looks like this,
[
{ "label": "Arwen" },
{ "label": "Bilbo Baggins" },
{ "label": "Boromir" },
{ "label": "Frodo Baggins" },
{ "label": "Peregrin Pippin Took" },
{ "label": "Samwise Gamgee" }
];

Assuming you're using the jQueryUI autocomplete method, you can provide the URL of the JSON to the source method and it will retrieve it for you automatically. Try this:
$("#locality").autocomplete({
source: 'http://localhost/project/jSonDocs/dataWhat.txt'
});
If you still prefer to retrieve the JSON manually (if you need to change the source after initialisation for example) then you can achieve it like this:
function codeAddress() {
jQuery.get('http://localhost/project/jSonDocs/dataWhat.txt', function (data) {
$('#locality').autocomplete('option', 'source', data);
});
}

Related

How to pass the path of my JSON using JStree? Can I use /create another treeview CRUD?

I'm using Jstree and trying to put my JSON to the code using a method who I created that get the path to the JSON but I don't have any success. Have another way using just ASP.net core to create a CRUD viewtree without using Jstree? If don't have, how can I make it works?
The code:
let data_2 = #Html.Raw(Json.Serialize(Model.texto2));
var teste = decodeURIComponent("#Html.Raw(Model.getFile())");
window.location = teste;
$(document).ready(function (){
//parte do ajax
//fim ajax
var dataJson = JSON.parse(data_2);
$('#html1').jstree(
{
"core": {
"themes": {
"variant": "large"
},
"max_children":2
},
"plugins": ["contextmenu", "dnd", "search",
"state", "types", "wholerow"],
"root": {
"valid_children": ["default"]
}
}
);
$('#html2').jstree(
{
"core": {
"themes": {
"variant": "large"
},
"max_children":2
},
"plugins": ["contextmenu", "dnd", "search",
"state", "types", "wholerow"],
"json_data": {
"ajax": {
"url": "",
"data": function (n) {
return {
id: n.attr ? n.attr("id") : 0
}
}
}
}
);
});
I tried to put my JSON (a simple JSON just to make it works firstly) into JStree to make a CRUD with the framework.
{
"root": {
"branche": "example"
}
}
Update: i finally solved my first problem! but now i have another problem:I need to transform that path (the get file()) into a URL path. How can i do it? The new edit:
$('#html2').jstree // "#Html.Raw(Model.getFile().Replace(#"\", "/"))", <-- the data
(
{
"core": {
"themes": {
"variant": "large"
},
'data':{
type: "POST",
url: "#Html.Raw(Model.getFile().Replace(#"\", "/"))",
contentType: "application/json; charset=utf-8",
success: function (data) {
data.d;
$(data).each(function () {
return { "id": this.id };
});
}
}
}
}
);

unable to push multiple values/ data to the angular 2-tree

i am having a dynamic json data & 3 buttons "feed data" it contains one set of dynamic data and button 2 " feed another data" it contains another set of dynamic data and button 3 is " Send data" here my issue when ever i press feed data and select option and press send data it is working and after that if i press feed another data and press send data then it is giving error"isSelected is undefined"
error simulation : feed data --> select option --> send data & press feed another data --> select options --> send data then we are getting error
options = {
useCheckbox: true
};
arrayData;
nodes;
data = {
"info": {
"laptop": {
},
"config": {
"properties": {
"ram": {
},
"processor": {
},
"hdd": {
}
}
},
"link": {
},
"name": {
},
"company": {
"properties": {
"model": {
},
"maker": {
"type": "integer"
},
"country": {
"type": "text"
},
"enterprise": {
}
}
}
}
};
dataa = {
"info": {
"mobile": {
},
"config": {
"properties": {
"ram": {
},
"processor": {
},
"storage": {
}
}
},
"link": {
},
"name": {
},
"company": {
"properties": {
"model": {
},
"maker": {
"type": "integer"
},
"country": {
"type": "text"
},
"enterprise": {
}
}
}
}
};
click(tree:TreeModel)
{
this.arrayData= [];
console.log(tree.activeNodes);
let result: any = {};
let rs = [];
// tree.selectedLeafNodeIds = {};
Object.keys(tree.selectedLeafNodeIds).forEach(x=>{
let node:TreeNode=tree.getNodeById(x);
if (node.isSelected)
{
if (node.parent.data.name) //if the node has parent
{
rs.push(node.parent.data.name+'.'+node.data.name);
if (!result[node.parent.data.name]) //If the parent is not in the object
result[node.parent.data.name] = {} //create
result[node.parent.data.name][node.data.name] = true;
}
else {
if (!result[node.data.name]) //If the node is not in the object
result[node.data.name] = {} //create
rs.push(node.data.name);
}
}
})
this.arrayData = rs;
}
feedData(){
const results = Object.keys(this.data.info).map(k => ({
name: k,
children: this.data.info[k].properties
? Object.keys(this.data.info[k].properties).map(kk => ({name: kk}))
: []
}));
this.nodes = results;
}
feedAnother(){
const results = Object.keys(this.dataa.info).map(k => ({
name: k,
children: this.dataa.info[k].properties
? Object.keys(this.dataa.info[k].properties).map(kk => ({name: kk}))
: []
}));
this.nodes = results;
}
when ever i press feed data and press send data then i am able to view the info and lie wise i want to update data i press feed another data then press send data then it needs to get the updated results
below is my stack blitz url : https://stackblitz.com/edit/angular-zapxko
You can simply change nodes object to update the result.
You need to use Async Data method to update nodes. Here are the demo and code from Angular Tree's official documentation.

How to call Angularjs controller function outside the controller in an Ajax call

Am trying to call Angularjs function outside the controller component like the below :
<script type="text/javascript">
function saveprof() {
$('.spinner').show();
$.ajax({
type: "POST",
url: "saveprof",
enctype: 'multipart/form-data',
async: true,
data: {
'rinput_Aj': JSON.stringify(angular.element(document.getElementById('rdExampleApp')).scope().$func()),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: function (data, textStatus, jqXHR) {
$('#message').html(data);
window.location.href = 'myprofile';
window.location('myprofile');
$('.spinner').fadeOut();
}
});
}
</script>
Here is the angularjs controller code :
<script>
var app = angular.module('rdExampleApp', ['ui.rdplot']);
app.controller('rdPlotCtrl', function ($scope) {
$scope.dataset = {
"d0": { "id": 0, "name": "Housing", "value": 18 },
"d1": { "id": 1, "name": "Travel", "value": 31.08 },
"d2": { "id": 2, "name": "Restaurant", "value": 64 },
"d3": { "id": 3, "name": "Bank", "value": 3 },
"d4": { "id": 4, "name": "Movies", "value": 10 }
};
$scope.func = function func() {
var jdata = $scope.dataset;
return jdata;
}
});
</script>
It throws an error
Uncaught TypeError: Cannot read property '$func' of undefined
EDIT:
After the suggestions, I converted my jquery ajax call to $http function in Angularjs.. But it does nothing.. No error in console :(
Here is how am invoking the $http service function
<body ng-controller="rdCtrl">
<a ng-click="saveprof()">Save</a>
<script>
var app = angular.module('rdExampleApp', ['ui.rdplot']);
app.controller('rdCtrl', function ($scope) {
$scope.dataset = {
"d0": { "id": 0, "name": "Housing", "value": 18 },
"d1": { "id": 1, "name": "Travel", "value": 31.08 },
"d2": { "id": 2, "name": "Restaurant", "value": 64 },
"d3": { "id": 3, "name": "Bank", "value": 3 },
"d4": { "id": 4, "name": "Movies", "value": 10 }
};
$scope.func = function func() {
var jdata = $scope.dataset;
return jdata;
}, function ($scope, $http) {
$scope.saveprof = function () {
//show spinner
$('.spinner').show();
$http.post('saveprof', {
data: { 'data': JSON.stringify($scope.dataset) }
})
.success(function (data) {
if (data == "null") {
//your code if return data empty
} else {
//your code if return data not empty
$('#message').html(data);
}
//hide spinner
$('.spinner').fadeOut();
})
.error(function (data, status, headers, config) {
console.log('error' + status);
//hide spinner in case of error
$('.spinner').fadeOut();
})
}
}
);
</script>
</body>
What am I missing?
in order to run XMLHttpRequest requests to the server you have many options in angularjs, you dont have to mess with simple javascript and call angular scope to get variables and functions.
you can do that either with $http or with services(leave it for now).
i am going to show how you can make the request with $http in native angular.
first of all you have to import the $http module on the declaration of your controller, like this :
var app = angular.module('rdExampleApp', ['ui.rdplot']);
app.controller('rdPlotCtrl', function ($scope,$http) {...});
into you controller you create the json object as you do it and then do the request like this:
//show spinner
$('.spinner').show();
$http.post('dal/addEventHalls.php', {
data: {'data': $scope.datase}
})
.success(function (data) {
if (data == "null") {
//your code if return data empty
} else {
//your code if return data not empty
}
//hide spinner
$('.spinner').fadeOut();
})
.error(function (data, status, headers, config) {
console.log('error' + status);
//hide spinner in case of error
$('.spinner').fadeOut();
})
as you can see we dont use url parameter but we pass the url directly into post() function. the data parameter is there to put whatever data you would like to send to the server.
hope helps good luck.
UPDATE
personally i dont stringify the data parameters.i pass them like json object
into php file , in order to get the data , try this:
$params = json_decode(file_get_contents('php://input'), true); //read values from angular factory-service

loading data in datatable on onchange event

I want to implement function in which data will be loaded into datatable after onChange event. So for that I am trying to implement code as below.
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
Which is creating my datatable layout and I am calling below function on dropdown change event is :
function loadFeedback(){
viewdatatabJS = $('#dataTablesFeedback').dataTable({
"processing" : true,
"retrieve" : true,
"ajax" : "/nhp/rest/feedback/viewFeedback",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "userName", "value":employeeId } ,
{ "name": "resourceId", "value":mentorDataJson[$('#dropDownId').val()].resourceId });
},
});
}
Where I am passing some parameter in aoData.push but my URL is not getting called.
I Solved the issue by simply implementing datatable properties. i wrote my code of datatable
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
in jsp document.ready(function()) and then on my request call of drop down change event i wrote below code on my javascript function.
$.ajax({
url : "",
type: 'GET',
contentType: "application/json",
data: {
'userName': value,
'resourceId' : value,
},
success: function(data) {
var table = $('#dataTablesFeedback').DataTable();
table.clear();
table.rows.add(data.data);
table.draw();
});
this way i first clear my datatable and then redraw it using my json which i got from my ajax call.
Thanks

Appending to JSON object using JavaScript

I'm building the JSON object using JavaScript. How would I inset the following data to the bottom of the stack:
"hello": { "label":"Hello", "url":"#hello" }
in to the following variable:
var ListData = {
"main": {
"label":"Main",
"url":"#main"
},
"project": {
"label":"Project",
"url":"#project"
},
"settings": {
"label":"Settings",
"url":"#settings",
"subnav":[
{
"label":"Privacy",
"url":"#privacy"
},
{
"label":"Security",
"url":"#security"
},
{
"label":"Advanced",
"url":"#advanced"
}
]
}
};
So the variable looks like:
var ListData = {
"main": {
"label":"Main",
"url":"#main"
},
"project": {
"label":"Project",
"url":"#project"
},
"settings": {
"label":"Settings",
"url":"#settings",
"subnav":[
{
"label":"Privacy",
"url":"#privacy"
},
{
"label":"Security",
"url":"#security"
},
{
"label":"Advanced",
"url":"#advanced"
}
]
},
"hello": {
"label":"Hello",
"url":"#hello"
}
};
I used the following code but it doesn't seem to work:
var NewData = '"hello": { "label":"Hello", "url":"#hello" }';
ListData.push(NewData);
You can insert it directly with an object literal:
ListData.hello = { label: "Hello", url: "#hello" };
If you are using jQuery, you can use the .extend() jQuery API like:
$.extend(ListData, {"hello": { "label":"Hello", "url":"#hello" }});
I have one more solution using underscore.js module,
var _ = require("underscore");
var src = {
"main": {
"label": "Main",
"url": "#main"
},
"project": {
"label": "Project",
"url": "#project"
},
"settings": {
"label": "Settings",
"url": "#settings",
"subnav": [
{
"label": "Privacy",
"url": "#privacy"
},
{
"label": "Security",
"url": "#security"
},
{
"label": "Advanced",
"url": "#advanced"
}
]
}
};
var dest = {"hello": { "label":"Hello", "url":"#hello" }};
var data = _.extend(src, dest);
console.log(JSON.stringify(data));
Required op :
{"main":{"label":"Main","url":"#main"},"project":{"label":"Project","url":"#project"},"settings":{"label":"Settings","url":"#settings","subnav":[{"label":"Privacy","url":"#privacy"},{"label":"Security","url":"#security"},{"label":"Advanced","url":"#advanced"}]},"hello":{"label":"Hello","url":"#hello"}}
Keeping with you object literal statements just add another object to your ListData object.
ListData.hello = { "label":"Hello", "url":"#hello" };
push is only for Javascript Arrays.
A JavaScript Object Literal is a comma-separated list of name/value pairs wrapped by a pair of curly braces.
To append the property name of encampment name with a value of Valley Forge to the bottom of the stack, simply add the property name after the JSON object with a dot syntax. Then specify the value. (See 'Append data' below)
You can also delete the appended name/value pair from the object literal. (See 'Delete data below')
// Start with some JSON
var myJson = { "name":"George Washington", "rank":"General", "serial":"102" };
// Append data
myJson.encampment = "Valley Forge";
// Delete data
delete myJson.encampment

Categories

Resources