Problems loading Json via $http using angularJS - json

I have son problems trying to load a Json in a contact App. (based in angular UI)
I'm new on AngularJS and I don't know where is the error (well, yes, the console sayme 'SyntaxError: Unexpected token i')
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.when("", "/contacts/list");
$urlRouterProvider.when("/", "/contacts/list");
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/contacts/list");
$stateProvider
.state('contacts', {
abstract: true,
url: '/contacts',
templateUrl: 'contacts.html',
controller: 'contactController',
onEnter: function(){
console.log("enter contacts");
}
})
.state('contacts.list', {
url: '/list',
// loaded into ui-view of parent's template
templateUrl: 'contacts.list.html',
onEnter: function(){
console.log("enter contacts.list");
}
})
.state('contacts.detail', {
url: '/:id',
// loaded into ui-view of parent's template
templateUrl: 'contacts.detail.html',
controller: function($scope, $stateParams){
$scope.person = $scope.contacts[$stateParams.id];
},
onEnter: function(){
console.log("enter contacts.detail");
}
})
.state('contacts.detail.test', {
url: '/test',
// loaded into ui-view of parent's template
templateUrl: 'contacts.detail.test.html',
onEnter: function(){
console.log("enter contacts.detail.text");
}
});
});
myapp.controller('contactController',function($scope, $http){
$scope.contacts = []; //declare an empty array
$http.get("contacts.json")
.success(function(response){
$scope.contacts = response; //ajax request to fetch data into $scope.data
});
});
Contents of contacts.json:
[{ id:0, name: "Alice" },
{ id:2, name: "Alirce" },
{ id:3, name: "Alwicse" },
{ id:4, name: "Awlice" },
{ id:1, name: "Bob" }]
I made a Plunkr for explain it well

As everyone's saying in the comments, JSON keys must be strings. Replace contacts.json with
[
{ "id":0, "name": "Alice" },
{ "id":2, "name": "Alirce" },
{ "id":3, "name": "Alwicse" },
{ "id":4, "name": "Awlice" },
{ "id":1, "name": "Bob" }
]
Here's a fixed Plunkr

Related

Access an axios data formatted as json from vue

I need to show data from a json response from get request. Vue part of my code is :
<script type="text/javascript">
var vm = new Vue({
el: '#app2',
delimiters: ['[[',']]'],
data: {
masa_data: {},
},
mounted: function() {
polling1=setInterval(function() {
axios.get('/order')
.then(function(response) {
vm.$data.masa_data = response.data;
})
}, 1000);
},
beforeDestroy () {
clearInterval(this.polling1)
}
});
</script>
masa_data comes from axios as below:
{ "Bahçe1": { "A": { "1": { "kisi_sayisi": "2", "siparisler": [ {
"adet": 2, "bolum": "drink", "satir": "Açık Çay" }, { "adet": 1,
"bolum": "tatli", "satir": "Kaymaklı Ekmek Kadayıfı" } ] },
When i want to show, for example, value of "kisi_sayisi", I could not figure out what to put inside html code below:
<p class="card-text">[[masa_data]]</p>
Try this.
<p class="card-text" v-if="Object.values(masa_data).length>0">[[masa_data.Bahce1.A['1']['kisi_sayisi'] ]]</p>
https://codepen.io/Pratik__007/pen/QWbjOxE?editors=1010

The componentDidMount is not getting called in reactjs

I'm trying the example in reactjs tutorial https://facebook.github.io/react/docs/tutorial.html to read the json from server(file). But, my "componentDidMount" is not getting called.
Below is the code:
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this),
cache: false
});
},
getInitialState: function() {
return {data: {}};
},
componentDidMount: function() {
this.loadCommentsFromServer();
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.content.map(function(comment) {
return (
<Comment pageName={comment.xyz} key={comment.id}>
{comment.abc}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var Comment = React.createClass({
render: function() {
return (
<div className="comment">
<h2 className="commentpageName">
{this.props.pageName}
</h2>
<p> {this.props.children} </p>
</div>
);
}
});
ReactDOM.render(<CommentBox url="/api/comments" />, document.getElementById('content'));
Please check the way I have initialized the data(data: {})
The "componentDidMount" gets called when the json is of the following type(Just the way in the tutorial):
[ {"id": "1", "xyz": "xyz1", "abc": "abc1"},
{"id": "2", "xyz": "xyz2", "abc": "abc2"} ]
But the json format I want is:
{
content: [
{"id": "1", "xyz": "xyz1", "abc": "abc1"},
{"id": "2", "xyz": "xyz2", "abc": "abc2"},
{"id": "3", "xyz": "xyz3", "abc": "abc3"}],
"totalPages":3,
"totalElements":10,
"last":true
}
Let me know in what conditions the componentDidMount doesn't get called. Please help.
In the "Networks" console of chrome developer tools, I don't see the call made to my json file.
When I added logs in my program, I see that getInitialState() gets called first, then render, then the error "Uncaught TypeError: Cannot read property 'data' of null" is shown.
I think your componentDidMount() is not called because your render code inside <CommentList> does not work on first render, because data is empty, and this.props.data.content probably does not exist, therefore your render fails.
What you probably should do is change this:
var commentNodes = this.props.data.content.map(function(comment) {
To this:
var commentNodes = [];
if (this.props.data.content) {
commentNodes = this.props.data.content.map(function(comment) {
...
}
componentDidMount() is always called after the first render (and not in subsequent renders)

Extjs create form items with json store

I have created a form panel view and I will create some form items iside this panel. The communication to the store, controller and model works fine but how can I create the items in the view?
Json array (retrieved from external service):
{
"data": [
{
"name": "ff",
"xtype": "textfield",
"allowBlank": false,
"fieldLabel": "labelText1"
},
{
"name": "fsdsdf",
"xtype": "textfield",
"allowBlank": false,
"fieldLabel": "labelText2"
}
],
"msg": "Unknown",
"success": true
}
Store:
Ext.define('myApp.store.Forms', {
extend: 'Ext.data.Store',
alias: 'store.Form',
model: 'myApp.view.FormModel',
constructor: function(config) {
var me = this;
config = config || {};
me.callParent([Ext.apply({
autoLoad: true,
proxy: {
type: 'ajax',
url: 'url_to_service',
reader: {
type: 'json',
rootProperty: 'data',
successProperty : 'success'
}
},
storeId: 'formStore'
}, config)]);
// console.error("store loaded");
// console.info(me);
}
});
model
Ext.define('myApp.view.FormModel', {
extend: 'Ext.data.Model',
data: {
name: 'myApp'
}
});
Controller
Ext.define('myApp.view.FormController', {
extend: 'Ext.app.ViewController',
alias: 'controller.form',
init: function(application) {
var store = new myApp.store.Forms();
store.on("metachange", metaChanged, this);
function metaChanged(store, meta) {
var grid = Ext.ComponentQuery.query('form')[0];
grid.fireEvent('metaChanged', store, meta);
};
this.control({
"form": {
metaChanged: this.handleStoreMetaChange
}
});
},
handleStoreMetaChange: function(store, meta) {
var form = Ext.ComponentQuery.query('form')[0];
form.reconfigure(store, meta.data);
}
});
At least the view where I want to create the items from the store.
Ext.define('myApp.view.Form', {
extend: 'Ext.form.Panel',
xtype: 'form',
controller: "form",
viewModel: {
type: "form"
},
title: 'form',
bodyPadding: 10,
autoScroll: true,
defaults: {
anchor: '100%',
labelWidth: 100
},
// How can I add form items here?
});
Within your view you'll need to create a function that matches the form.reconfigure(store, meta.data) call you are making in your controller.
And in that function you can call the form's add function to add items to the form. As you are already supplying the xtype and configuration parameters in the data structure each item can be passed to the add function as it. It would look something like the below code...
reconfigure: function(store, data) {
var me = this;
Ext.each(data, function(item, index) {
me.add(item);
});
}
I have knocked together an Example Fiddle that shows this working. I just mocked out the loading of the data and 'metachange' event as it was easier to get the demo working.

$scope issue with gridOptions, angular-ui-grid and REST call from service

I seem to be having an issue getting my ng-grid directive to populate from a returned REST api json obj.
I have verfied that a valid json obj is returned and i have retrieved a nested obj of the data I need. It seems that it is not making it into the gridOptions function. Where myData is the correct valid json.
Any help will be greatly appreciated. I am pulling my hair out at this point.
Here is my service:
grid-service.js
'use strict';
app.factory('GridService', ['$http', '$q', function($http, $q) {
var apiUrl = "http://xx.xx.xx.xx/coName/public/index.php/";
// configure the send request
function sendRequest(config){
var deferred = $q.defer();
config.then(function(response){
deferred.resolve(response);
}, function(error){
deferred.reject(error);
});
return deferred.promise;
}
// retrieve all
function getRoles() {
var request = $http({
method: 'GET',
url: apiUrl + 'roles'
});
return sendRequest(request);
}
return {
getRoles: getRoles
};
}]);
I inject it into my ctrl here, and my init function and gridOption functions:
app.controller('ModuleCtrl', [ '$scope', '$http', '$modal', '$filter', 'GridService', function($scope, $http, $modal, $filter, gridService) {
var initializeGrid = function(){
getRoles();
};
var getRoles = function(){
gridService.getRoles().then(function(myRoles){
var myRolesData = myRoles.data._embedded.roles;
$scope.myData = myRoles.data._embedded.roles;
console.log($scope.myData);
});
};
$scope.gridOptions = {
data: 'myData',
enableRowSelection: true,
enableCellEditOnFocus: true,
showSelectionCheckbox: true,
selectedItems: $scope.selectedRows,
columnDefs: [{
field: 'ID',
displayName: 'Id',
enableCellEdit: false
}, {
field: 'APP_ID',
displayName: 'Module ID',
enableCellEdit: false
}, {
field: 'RLDESC',
displayName: 'Role Description',
enableCellEdit: true
}, {
field: 'APDESC',
displayName: 'Module Description',
enableCellEdit: true
}, {
field: 'ZEND_DB_ROWNUM',
displayName: 'Record number',
enableCellEdit: false
}]
};
// fire it up
initializeGrid();
}
My complete json:
{
"_links": {
"self": {
"href": "http://xx.xx.xx.xx/coName/public/index.php/roles?page=1"
},
"describedBy": {
"href": "Some Fun Stuff"
},
"first": {
"href": "http://xx.xx.xx.xx/coName/public/index.php/roles"
},
"last": {
"href": "http://xx.xx.xx.xx/coName/public/index.php/roles?page=1"
}
},
"_embedded": {
"roles": [
{
"ID": 1,
"APP_ID": 1,
"RLDESC": "Admin",
"APDESC": "authLive",
"ZEND_DB_ROWNUM": "1"
},
{
"ID": 2,
"APP_ID": 1,
"RLDESC": "User",
"APDESC": "authLive",
"ZEND_DB_ROWNUM": "2"
},
{
"ID": 4,
"APP_ID": 1,
"RLDESC": "SuperUser",
"APDESC": "authLive",
"ZEND_DB_ROWNUM": "3"
}
]
},
"page_count": 1,
"page_size": 25,
"total_items": 3
}
Remove the following line from the gridOptions
data: 'myData'
Then in getRoles() use
$scope.gridOptions.data = myRolesData;
instead of
$scope.myData = myRoles.data._embedded.roles;
(Maybe you need $scope.myData for some other reason than the grid, but if not I think the above is all you need. I have not tested this live, but it should work.)

how to add json to backbone,js collection using fetch

I am trying to get backbone.js to load json.
The json loads but i am not sure how to get the items into my collection.
Or maybe that happens automatically and i just can't trace out. scope issue?
//js code
//model
var Client = Backbone.Model.extend({
defaults: {
name: 'nike',
img: "http://www.rcolepeterson.com/cole.jpg"
},
});
//collection
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json'
});
//view
var theView = Backbone.View.extend({
initialize: function () {
this.collection = new ClientCollection();
this.collection.bind("reset", this.render, this);
this.collection.bind("change", this.render, this);
this.collection.fetch();
},
render: function () {
alert("test" + this.collection.toJSON());
}
});
var myView = new theView();
//json
{
"items": [
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
}
Your json is not in the correct format, you can fix the json or add a hint to backbone in the parse method:
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json',
parse: function(response){
return response.items;
}
});
Or fix your JSON:
[
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
If you use rest api, try turn off these parameters:
Backbone.emulateHTTP
Backbone.emulateJSON