AngularJS $http.get not pulling back - javascript

Why is this not pulling back anything? I keep getting the error message and I cannot figure out why. I tried to use JSONParse on the response data and reassigning it to the $scope but that didn't help. I have no errors in my F12 Console. I know JQuery is a much better solution but I prefer the Javascript, i'll take both though. Thanks ahead of time.
var controlSeletor = angular.module('moduleName', []);
controlSeletor .controller('variableController', function($scope, $http) {
$http.get("data.json")
.then(
function(response) {
// Success
$scope.variable = response.data;
},
function(response){
// Error
alert("Error!");
}
);
});
The json is a separate file and looks like this:
[{
"url": "place.html",
"name": "Bob",
"pic": "bob.jpg"
},
{
"url": "place.html",
"name": "Mike",
"pic": "mike.jpg"
},
{
"url": "place.html",
"name": "Tony",
"pic": "tony.jpg"
}];

Your JSON is not valid, change it as follows,
[ {
"url": "place.html",
"name": "Bob",
"pic": "bob.jpg" }, {
"url": "place.html",
"name": "Mike",
"pic": "mike.jpg" }, {
"url": "place.html",
"name": "Tony",
"pic": "tony.jpg" } ]
var app = angular.module('filterApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get('data.json').
then(function(response) {
$scope.variable = response.data;
});
});
DEMO

Few observations :
Controller declaration is not correct. It should be controlSeletor.controller instead of controlSeletor .controller.
Your JSON is not a valid JSON.
Valid JSON should be like this :

Related

Extract information from json

So I have the following object from my controller, which has a name, a list of beans and a list of operations:
{
"name": "Charge",
"beans": [
],
"operations": [
{
"name": "getSize",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
]
},
{
"name": "truncate",
"returnType": "java.lang.Void",
"description": "empty description",
"parameters": [
]
},
{
"name": "count",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
{
"name": "javaCode",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "update",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
{
"name": "javaSelectCode",
"type": "java.lang.String",
"value": null
},
{
"name": "javaUpdateCode",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "delete",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
{
"name": "javaCode",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "dump",
"returnType": "java.lang.Void",
"description": "empty description",
"parameters": [
{
"name": "javaSelectCode",
"type": "java.lang.String",
"value": null
},
{
"name": "destinationPath",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "select",
"returnType": "java.lang.String",
"description": "empty description",
"parameters": [
{
"name": "javaCode",
"type": "java.lang.String",
"value": null
}
]
}
],
"$$hashKey": "object:620"
}
Basically I want to display all the operations from this object in a dropdown menu.
So I was thinking of having something like:
<div ng-repeat="operation in object.operations">
{{operation.name}}
</div>
Except the code above doesn't display anything on the screen, no errors in the console, nothing.
Any help would be much appreciated!
EDIT:
Javascript service:
app.controller('selectAll', ['$http', '$scope' , '$rootScope', function ($http, $scope, $rootScope) {
$scope.response;
$scope.operations;
$rootScope.$on("invokeSelectAll", function(){
$scope.invokeSelectAll();
});
$scope.invokeSelectAll = function(){
$scope.response = $http.post('/invoke/selectAll/', $rootScope.dataObj);
$scope.object = JSON.stringify($rootScope.object);
console.log(" object operation from selectAll " + $scope.object);
$scope.response.then(function(data) {
$scope.responses = data.data ? data.data : "Select Operation not supported on this bean";
});
}
}]);
Screenshot of dev console:
https://imgur.com/a/8WAAL
Use JSON.stringify() to create a JSON string from a JavaScript object.
Use JSON.parse() to parse a JSON string to a JavaScript object.
In your case, you need to use JSON.parse() because you get a JSON string from the server and want to parse it to a JavaScript object.
$scope.object = JSON.parse($rootScope.object);
you are using JSON.stringify which is used to change javascript object to string and store it as a string only.
You should Parse the data with JSON.parse(), and the data becomes a JavaScript object. and you can easily use that in ng-repeat.
Try it ,It will work fine

How to interpret javascript within a json file

I'm working with the form builder Alpaca, and I would like to interpret a javascript function within a json datasource file, to select a certain file :
/data/options.json :
"nature":{
"type": "select",
"dataSource": "function(e) {...}"
},
This file is loaded here :
/test.html :
$("#div").alpaca({
"optionsSource": "/data/options.json",
etc...
Is this possible ?
Thanks.
You can use eval as said :
object = {"nature":{
"type": "select",
"dataSource": "function(e) {alert('ok')}"
}
}
var x = eval("("+object.nature.dataSource+")");
x()
Demo
You could make the function call first, then add the result to you JSON with data.nature.push();
See this answer : Add data to JSON in JS
script type="text/javascript">
var JSON = {"nature":{
"type": "select"
}};
JSON.dataSource.push(function());
$("#form1").alpaca(JSON);
</script>
As the Alpace datasources doc, http://www.alpacajs.org/docs/api/datasources.html you can use custom function in the datasource parameter :
$("#field5").alpaca({
"schema": {
"type": "string",
"title": "Pick an Action Hero"
},
"options": {
"type": "select",
"dataSource": function(callback) {
callback([{
"value": "rambo",
"text": "John Rambo"
}, {
"value": "norris",
"text": "Chuck Norris"
}, {
"value": "arnold",
"text": "Arnold Schwarzenegger"
}]);
}
}
});

How to parse json response in javascript?

After making a call to rest api I am getting this data in javascript.
{
"error": false,
"orders": [
{
"oid": "764",
"cid": "423",
"name": "Akshay jain",
"address": "infront of gwal magra talab",
"mobile": "11111111",
"email": "abcd#gmail.co",
"odate": "2016-03-28 21:50:45",
"status": "NEW ORDER",
"payment": "1",
"ddate": "2016-03-28",
"dtime": "1"
},
{
"oid": "763",
"cid": "438",
"name": "Vishwakarma Ji",
"address": "Narayan Pura Road",
"mobile": "0000000000",
"email": null,
"odate": "2016-03-28 20:02:06",
"status": "Confirmed (Ready for Delivery)",
"payment": "1",
"ddate": "2016-03-28",
"dtime": null
}
]
}
This is how i am storing in controller.
$scope.result = Order.query(); // where Order is a service in angularjs
If i am trying to print $scope.result.error it is giving object object not the actual error value.
How to parse error and orders in javascript and save it in a variable?
If this Order.Query is async, you have to set the result in a callback
app.controller("OrderIndexCtrl",function($scope,Order) {
Order.query(function(data){
if(data.error == false) {
$scope.result = data.orders;
}
else {
...
}
});
});
Try using the following code.
$scope.result = JSON.parse(Order.query());
Source: this question

Angular js injection error when app is loaded on browser

I get this error: [$injector:modulerr] http://errors.angularjs.org/1.3.0/$injector/modulerr?p0=myTmoApp.pdl&p1=Err…rkspace%2Fnetbeans-workspace%2FJsonParsing%2Fweb%2Fangular.min.js%3A18%3A3)
I have properly injected all services and scopes but still I get this error when I run the app.
Here is the code:
var app = angular.module("myTmoApppdl", []);
app.controller("myCtrl", function ($scope, jsonParsingService) {
var digitalData = digitalData || {};
digitalData =
{
"page": {
"pageInfo": {
"pageID": "12345",
"pageName": "smartphones:samsung-galaxy-s-5",
"pageURL": "www.t-mobile.com/products/smartphonesSamsungGalaxyS5",
"previousPageURL": "www.t-mobile.com/products/smartphones",
"prevPageName": "phones",
"version": "1.15",
"language": "en-US",
"geoRegion": "US",
"domain": "t-mobile.com",
"responsiveState": "desktop",
"timeStamp": "2015-03-23T20:52:23.563Z",
"currencyCode": "USD"
},
"category": {
"primaryCategory": "shop",
"subCategory": ["smartphones"],
"pageType": "product details",
"variant": "",
"channel": "",
"subChannel": "",
"flowName": "",
"storeID": "",
"referringApp": "tapestry"
},
"search": {
"searchTerm": "",
"searchResultCount": 0
}
}
};
digitalData = JSON.stringify(digitalData);
console.log("json to be parsed is: " + digitalData);
$scope.myTxt = "You have not parsed json yet";
$scope.myFunc = function () {
jsonParsingService.parseMyJson(digitalData);
$scope.myTxt = "Json parsing complete!";
console.log("Json parsing complete");
};
});
Service:
app.service('jsonParsingService', function () {
this.parseMyJson = function (json) {
var obj = JSON.parse(json);
console.log(obj);
};
});
It is just a sample app I am trying to run but unable to figure out what went wrong
Script files:
<script src="https://code.angularjs.org/1.3.0-rc.2/angular.min.js"></script>
<script src="parseJson.js" type="text/javascript"></script>
You have to pass in the service in the following format to the Controller. See the array notation.
.controller('myCtrl', ['$scope', 'jsonParsingService',function($scope,jsonParsingService){
//controller code here
}]);
See the docs about Dependency Injection here
It seems that your angular.js wasn't available. Please see a running example in this bin

json, ajax with a hash

i wondering if there any solution to get data from json in this format:
{ "#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">":[{"id":68,
"name":"johnny",
"description":"Hello my first Description",
"created_by_user_id":16530,
"created_at":"2016-01-28T13:17:51.827Z",
"updated_at":"2016-01-29T10:40:40.011Z",
"receiver_group_id":3,"dynamic_fields":{
"files":[
{
"id":2,
"date":"2016-01-29T10:40:35.720Z",
"path":"http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public":null
}
]} }]}
like i want to have a name and description. but if i call in ajax like this:
$(function(){
$.ajax({
url: './dataModel.json',
dataType: 'json',
method: 'GET',
success: function(data){
console.log(data[0].name);// error name is not defined
console.log(data.name); // undefined
}
});
})
may be you guys have some idea how can i get the name and description? thank you so much for any kind of suggestion and idea.
best regard,
ape
Try this:
var input = {
"#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">": [{
"id": 68,
"name": "johnny",
"description": "Hello my first Description",
"created_by_user_id": 16530,
"created_at": "2016-01-28T13:17:51.827Z",
"updated_at": "2016-01-29T10:40:40.011Z",
"receiver_group_id": 3,
"dynamic_fields": {
"files": [{
"id": 2,
"date": "2016-01-29T10:40:35.720Z",
"path": "http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public": null
}]
}
}]
};
var output = Object.keys(input).map(function(key) {
return input[key];
})[0];
alert(output[0].name);

Categories