Getting JSON data using $http - javascript

I am trying to get the JSON data using the $http function; I am always getting error for this. Here is my HTML code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in code">
{{ x.code }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("data.json")
.success(function (response) {$scope.code = response;})
.error(function (response) {alert("Error")})
});
</script>
</body>
</html>
Here is my data.json file:
{
"code":"#include <stdio.h>
int main()
{
printf('Hello world');
return 0;
}"
}
Here is the plunker http://plnkr.co/edit/Q4dsCjHM3ykgp2SaHw35?p=preview

Do change your data to below.Basically it should be string, use pre tag for line break & then replace enter by \n
{
"code": "#include <stdio.h>\n int main()\n printf('Hello world');\n return 0;\n}"
}
HTML
<ul>
<li ng-repeat="x in code">
<pre>{{ x }}</pre>
</li>
</ul>
Working Plunkr

Your JSON is poorly formatted. The string line of code should be on one line e.g.,
{
"code": "#include <stdio.h> int main() ...."
}
You can always validate your JSON at jsonlint.com

Your JSON is not well formated.
JSON
{
"code":"#include <stdio.h>int main(){printf('Hello world');return 0;}"
}
Then, you can access to the code field in your request :
Controller
$http.get("data.json")
.success(function (response) {
$scope.code = response.code;
})
.error(function (response) {
alert("Error");
});

Related

Retrieving JSON data from API using AngularJS

I'm trying to get data from a Web API and display it in a table, but it doesn't work.
I am new to angularjs and i code simple program to get data from the Web API and display in table.but i am not able to get data.
Module
var app = angular.module("myApp", []);
Service
app.service("myService", function ($http) {
//get All Eployee
this.getEmployees = function () {
return $http.get('http://apidemo.gouptechnologies.com/api/admin');
};
})
Controller
app.controller("myCntrl", function ($scope, myService) {
$scope.divEmployee = false;
GetAllEmployee();
function GetAllEmployee() {
alert('home');
var getData = myService.getEmployees();
getData.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('Error in getting records');
});
}
});
The JS code is included in the head tag of the HTML file.
HTML body
<body>
<div ng-app="myApp" ng-controller="myCntrl">
<ul>
<li ng-repeat="x in employees">
{{ x.username + ', ' + x.password }}
</li>
</ul>
</div>
</body>
The API URL is legitimate.
Thanks.
Let example a json file in "data/branchList.json" directory, And i am trying to access all data from json file using $http.
It may help you to call a rest service aslo. check this example
data/branchList.json
[
{
"branch_id": 1,
"branch_name": "Mummbai",
"branch_address": "India"
},
{
"branch_id": 2,
"branch_name": "New York",
"branch_address": "US"
}
]
Controller
angular.module('myApp')
.controller('myCntrl', ['$http', '$state', function ($http, $state) {
'use strict';
var vm = this;
function init(){
vm.branchs = '';
loadBranch();
}
init();
function loadBranch(){
$http.get('data/branchList.json').success(function(response){
vm.branchs = response;
})
}
}]);
In this example i am storing all the data in vm.branches variable, you can use this variable in html page
HTML
<li class="col-sm-6" ng-repeat = "branch in vm.branchs">
<strong>{{branch.branch_name}}</strong>
<span>{{branch.branch_address}}</span>
</li>

$http is not defined

I am new to Angular JS and have getting below error when I have tried to inject $http service in the project. Please see the code file below.
As you can see I have created a <ng-app="myapp"> and created a controller for the same. As described in the tutorial I have registered the controller in the View.js and tried to load 'data.json' file data. However, during running the program I am getting error as $http is not defined.
View.html
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="js/View.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="Object">
<span ng-bind="o.rollNo"></span>
<span ng-bind="o.firstName"></span>
<span ng-bind="o.middleName"></span>
<span ng-bind="o.lastName"></span>
<span ng-bind="o.className"></span>
<span ng-bind="o.schoolName"></span>
</div>
</body>
</html>
View.js
var app=angular.module("myapp", []);
app.controller('Object',function($scope,$http) {
$http.get("data.json")
.success( function(response) {
$scope.o= response;
});
});
data.json:
[
{
"rollNo" : "1",
"firstName" : "ABC",
"middleName" : "DEF"
"lastName" : "HIJ"
"className" : "First"
"schoolName" : "CRB"
}
]
Project Structure
No problem with your code, it's working properly.
Since you have only 1 object, you need to get values based on index i.e o[0].rollNo
<body ng-app="myapp">
<div ng-controller="Object">
<span ng-bind="o[0].rollNo"></span>
<span ng-bind="o[0].firstName"></span>
<span ng-bind="o[0].middleName"></span>
<span ng-bind="o[0].lastName"></span>
<span ng-bind="o[0].className"></span>
<span ng-bind="o[0].schoolName"></span>
</div>
</body>
Controller
var app=angular.module("myapp", []);
app.controller('Object',function($scope,$http) {
$http.get('data.Json').
success(function(data, status, headers, config) {
alert("Success");
$scope.o = data;
}).
error(function(data, status, headers, config) {
alert("Error");
// log error
});
});
data.Json
You need to add comma between each key:value
[
{
"rollNo" : "1",
"firstName" : "ABC",
"middleName" : "DEF",
"lastName" : "HIJ",
"className" : "First",
"schoolName" : "CRB"
}
]
As per your project structure, your json file path(js/data.json)
$http.get('js/data.Json').
success(function(data, status, headers, config) {
alert("Success");
$scope.o = data;
}).
error(function(data, status, headers, config) {
alert("Error");
// log error
});
Since this was not yet mentioned in an answer, only in two comments:
You might need to move the line
<script src="js/View.js"></script>
to the bottom
<span ng-bind="o[0].schoolName"></span>
</div>
<script src="js/View.js"></script>
</body>
</html>
... see also #Pratap's answer concerning the JSON file.
Try this:
var app=angular.module("myapp", []);
app.controller('Object', objectCtrl);
objectCtrl.$inject = ['$scope', '$http'];
function objectCtrl($scope, $http){
$http.get("data.json")
.success( function(response) {
$scope.o= response;
});
}

AngularJs read json file

I have a tree which is created dynamically with json.There is a one controller and in this controller there is a json array.I use this json to create a tree,but i need to read this json from file externally.
My controller;
..........
$scope.myjson =
{
"option1": [
{
"child":[{"label":"Test1" },{"label":"Test2"}],
"id": "option1"
}
],
"option2": [
{
"child":[{"label":"Test1.1",}],
"id": "option2"
}
],
...........
}
Json array reading part(In Controller);
angular.forEach($scope.myjson, function(value, key)
{
if (key === 'option1')
{
for(var t=0;t<$scope.myjson[key][0].child.length;t++)
{
......Somethings.........
}
}
I want to call json file and read it to create a tree.How can i call json file and read in angularjs?
Reading JSON in Angular is pretty straightforward with $http. Keep in mind that $http will return a promise, and you need to resolve it before processing.
Here is a sample code:
$http.get('assets/messages.json').then(function (data) {
/** work with data **/
});
Here you can get a complete tutorial regarding your problem. You just need to modify it in your way.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
});
</script>

Use of Undefined Constant - assumed id

I am new to angularjs and am having some trouble implementing a simple checklist.
<html lang="en" ng-app>
<body>
<div ng-controller="IdController" class="id-contain">
<ul>
<li ng-repeat="id in ids">{{ id.body }}</li>
</ul>
</div>
</body>
</html>
and in my main.js I have
function IdController($scope) {
$scope.id = [
{ body: 'some' },
{ body: 'boiler' },
{ body: 'plate' }
];
}
However, when I load the page, i get Use of undefined constant id - assumed 'id' Any ideas on where I could have gone wrong?
Edit: I have adjusted the name in the controller from $scope.id to $scope.ids to no avail and when I change the {{}} to [[]] it loads [[ id.body ]] 3 times, but not the value. When I run it with {{}} it is giving me the same error and is parsed as <?php echo id.body; ?>
Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the # symbol to inform the Blade rendering engine an expression should remain untouched.
https://laravel.com/docs/8.x/blade#blade-and-javascript-frameworks
Use #before your angular {{}} blocks:
Your code would be like:
<html lang="en" ng-app>
<body>
<div ng-controller="IdController" class="id-contain">
<ul>
<li ng-repeat="id in ids"> #{{ id.body }} </li>
</ul>
</div>
</body>
</html>
That's a problem with blade, you can change laravel's config for blade template token from {{}} to something else like [[]]
Blade::setContentTags('[[', ']]');
Blade::setEscapedContentTags('[[[', ']]]');
Plus, in your angularjs code you should rename $scope.id to $scope.ids in your controller
UPDATE Blade tokens
EDIT OR you can override angular's tags delimiters
DEMO
HTML:
<div ng-app="main">
<div ng-controller="IdController" class="id-contain">
<ul>
<li ng-repeat="id in ids">[[id.body]]</li>
</ul>
</div>
</div>
JS:
angular.module('main', [])
.config(function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
})
.controller('IdController', function ($scope) {
$scope.ids = [
{ body: 'some' },
{ body: 'boiler' },
{ body: 'plate' }
];
});
You html is parsed with the blade parser, if you dont need this page to be parsed with blade parser rename your file from myfield.blade.php to myfile.php

How to write an angularJs Controller to GET Rest Data from Parse.com

See solution below:
I'm trying to connect to a Parse.com Rest backend and display data from object values.
HTML (I put several angular calls to be sure to catch output):
<div ng-controller="MyController">
<p>{{item}}<p>
<p>{{items}}<p>
<p>{{item.firstName}}<p>
<p>{{data}}<p>
</div>
JAVASCRIPT rest:
function MyController($scope, $http) {
$scope.items = [];
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional/id', headers: { 'X-Parse-Application-Id':'XXXX', 'X-Parse-REST-API-Key':'YYYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
});
};
}
This won't work, it does strictly nothing, not even a message in the console.
I know the rest call got the correct credential, as I'm able to get object content returned when I test it with a rest tester program. Maybe the URL should not be absolute ?
Any clue is very welcome, i've spent DAYS on that.
SOLUTION:
Thanks to the help of people answering this thread, I was able to find the solution to this problem so I just wanted to contribute back:
Get Json object data from Parse.com backend, pass it authentification parameters:
function MyController($scope, $http) {
$scope.items = [];
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional', headers: { 'X-Parse-Application-Id':'XXX', 'X-Parse-REST-API-Key':'YYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
});
};
Notice that ' ' necessary arround header key object values. Those ' ' are not necessary around method and url keys.
Template that list all 'firstName' of each object:
<div ng-controller="MyController" ng-init="getItems()">
<ul>
<li ng-repeat="item in items.results"> {{item.firstName}} </li>
</ul>
</div>
Notice: "item in items.results". "results" is necessary because the return value is a JSON object that contains a results field with a JSON array that lists the objects. This could save you some headache.
Also notice "ng-init": if you don't put that, or any other form of call to the getItem(),then nothing will happen and you will be returned no error.
That was my first try of Angularjs, and i'm already in love ^^.
Based in your request the controller should be:
HTML
<div ng-controller="MyController">
<button type="button" ng-click="getItems()">Get Items</button>
<ul>
<li ng-repeat="item in items"> item.firstName </li>
</ul>
</div>
JS
function MyController($scope, $http) {
$scope.items = []
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Users', headers: { 'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
})
}
}
Just a little update to the newer versions of Angular (using .then since version 1.5):
myApp.controller('MyController', function($scope, $http) {
$scope.items = []
$http({
method: 'GET',
url: 'https://api.parse.com/1/classes/Users',
headers: {'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}
})
.then(function successCallback(response) {
alert("Succesfully connected to the API");
$scope.items = data;
}, function errorCallback(response) {
alert("Error connecting to API");
});
});
var app = angular.module("app",[]);
app.controller("postcontroller", function($scope, $http){
$scope.getAllProjects = function() {
var url = 'https://reqres.in/api/products';
$http.get(url).then(
function(response) {
$scope.projects = response.data.data;
},
function error(response) {
$scope.postResultMessage = "Error with status: "
+ response.statusText;
});
}
$scope.getAllProjects();
});
<div ng-app="app">
<div ng-controller="postcontroller">
<div class="panel-body">
<div class="form-group">
<label class="control-label col-sm-2" for="project">Project:</label>
<div class="col-sm-5">
<select id="projectSelector" class="form-control">
<option id="id" ng-repeat="project in projects"
value="{{project.id}}">{{project.name}}</option>
</select>
</div>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>

Categories