Fetching JSONP with Angular.js - javascript

<html ng-app="movieApp">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
var base = 'http://api.themoviedb.org/3';
var service = '/movie/862';
var apiKey = '####';
var callback = 'JSON_CALLBACK';
var url = base + service + '?api_key=' + apiKey + '&callback=' + callback;
var movieApp = angular.module('movieApp', []);
movieApp.controller('MovieCtrl', function ($scope, $http){
$http.jsonp(url).then(function(data) {
$scope.movies = data;
});
});
</script>
</head>
<body style="padding:12px;" ng-controller="MovieCtrl">
<div ng-repeat="movie in movies">
<h1>{{movie.title}} {{movie.id}}</h1>
<p>{{movie.overview}}</p>
<img ng-src="http://image.tmdb.org/t/p/w500{{movie.poster_path}}" style='width:200px'/>
</div>
</body>
</html>
Trying to fetch JSON with Angular.js. The information is coming across fine but statuses I believe is also coming across. Resulting in 5 images being placed on the screen, 4 broken and 1 good image along with the data. How can I avoid sending this extra data?

Requesting JSON data with AJAX
You wish to fetch JSON data via AJAX request and render it.
Implement a controller using the $http service to fetch the data and store it in the scope.
<body ng-app="MyApp">
<div ng-controller="PostsCtrl">
<ul ng-repeat="post in posts">
<li>{{post.title}}</li>
</ul>
</div>
</body>
var app = angular.module("MyApp", []);
app.controller("PostsCtrl", function($scope, $http) {
$http.get('data/posts.json').
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
http://fdietz.github.io/recipes-with-angular-js/consuming-external-services/requesting-json-data-with-ajax.html

Related

How to assign data to variable in ajax success call in angularjs?

Hi I am developing Angularjs application. In ajax call i am getting data and i want to assign that data to variable but i am getting data as[object object].
Below is the data i am getting
{"data":{"ID":64,"OTP":2112},"status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://192.168.0.213:1234/api/CheckUSer","data":{"FirstName":"dfd","LastName":"fdf","Gender":"Male","DateOfBirth":"2017-04-04","Nationality":"India","Mobile_CountryCod":"376","MobileNumber":"444","EmailId":"sdsdffffff","IsMobileVerified":false,"IsEmailVerified":false,"Home_Location":"q","Home_City":"q","Home_Neighbourhood":"q","Home_HouseNumber":"q","Home_MainStreet":"q","Home_SubStreet":"q","Work_Location":"q","Work_City":"q","Work_Neighbourhood":"q","Work_HouseNumber":"q","Work_MainStreet":"q","Work_SubStreet":"q","RequestedPlatform":"Web","RequestedLanguage":"English"},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"OK"}
Below is my code,
$http.post('http://192.168.0.213:1234/api/CheckUSer', RegistrationData).then(function (response) {
alert(JSON.stringify(response));
var customerid = response.data.ID;
var OTP = response.data.OTP;
$state.go('Registration.OTPVerification', response);
}
Any help would be appreciated. Thank you.
Assuming your code is in a controller
script.js
angular.module('app', []);
angular.module('app')
.controller('ExampleController', ['$scope', function($scope) {
$http.post('http://192.168.0.213:1234/api/CheckUSer', RegistrationData).then(function (response) {
$scope.customerid = response.data.ID;
$scope.OTP = response.data.OTP;
}
}]);
index.html
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
customerid = {{customerid}}, OTP = {{OTP}}
</body>
</html>

MVC Controller method call from Angularjs return View HTML instead of JSON result

I have the following Controller method under HomeController,
[HttpGet]
public ActionResult GetStudents()
{
Student std1 = new Student();
List<Student> stdlst = new List<Student>();
std1.Id = 1;
std1.Name = "Emmanuvel";
std1.Age = 25;
stdlst.Add(std1);
Student std2 = new Student();
std2.Id = 2;
std2.Name = "Michael";
std2.Age = 24;
stdlst.Add(std2);
Student std3 = new Student();
std3.Id = 3;
std3.Name = "Hannah";
std3.Age = 22;
stdlst.Add(std3);
return Json(stdlst, JsonRequestBehavior.AllowGet);
}
And I'm calling this method using Angularjs Ajax function as below,
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.ButtonClick = function () {
$http.get('#Url.Action("GetStudents","Home")')
.success(function (data) {
$scope.students = data;
console.log($scope.students);
})
.error(function (data) {
console.log(data);
});
}
});
</script>
unfortunately, the console.log printing the View Page's HTML code, instead of the JSON data. Here is the console.log output,
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div ng-app="MyApp" ng-controller="MyController">
<input type="button" value="Submit" ng-click="ButtonClick()"/>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.ButtonClick = function () {
$http.get('/Home/GetStudents')
.success(function (data) {
$scope.students = data;
console.log($scope.students);
})
.error(function (data) {
console.log(data);
});
}
});
</script>
</body>
</html>
Help me to understand the wrong I did in this code.
there are a number of changes I would do there.
First separate the angular code from your view. You probably did it to be able to use the Razor syntax to build the URL but now you have a dependency on that.
What I would do is this :
move the angular controller into it's own file.
change the JavaScript URL to '/Home/GetStudents'
change the return type of your backend controller to JsonResult, instead of ActionResult. Even if you are passing Json in the result, because it's ActionResult, it will still come back with the HTML of the page.
Once you do all this, first check in the browser that you are receiving the proper data by calling the '/Home/GetStudents' URL yourself. Once you are sure, then add some breakpoints and make sure Angular is receing the data properly and then continue from there.

Angular js does not get json response from node js

I am trying to establish REST connection between node (middleware) and angular (UI). However, the json is displayed on the browser rather than being routed via the angular controller/html
Node/Express router.js
router.get('/members', function(request, response){
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET, POST");
response.setHeader('Content-Type', 'application/json');
var dbdata = [];
var str;
db.get('_design/views555/_view/app_walltime', function (err, body) {
if (!err) {
body.rows.forEach(function(doc) {
dbdata.push({name: doc.key, walltime:doc.value});
});
console.log(dbdata);
response.json(dbdata);
Angular controllers.js
'use strict';
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.config(['$httpProvider', function($httpProvider, $routeProvider, $locationProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http, $templateCache) {
alert('asdsad');
$scope.list = function() {
alert('hereh');
var url = 'http://192.168.59.103:8072/members';// URL where the Node.js server is running
$http.get(url).success(function(data) {
alert(data);
$scope.phones = data;
});
};
$scope.list();
});
html - testangular.js
<html ng-app="phonecatApp">
<head>
<meta charset="utf-8">
<title>My HTML File</title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css">
<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/angular-route/angular-route.min.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-controller="PhoneListCtrl">
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<ul class="phones">
<li ng-repeat="phone in phones | filter:query">
{{phone.name}}
<!--<p>{{phone.walltime}}</p> -->
</li>
</ul>
</div>
</div></div>
What is see is the following on the browser
[{"name":"app1","walltime":"1050"},{"name":"app2","walltime":"30"}]
I seem to be missing some configuration to let node and angular communicate. Please let me know what I am doing wrong.
What you see on the browser's window is a JSON object, that is the result of your request.
With the line $scope.phones = data;, you're simply assigning to $scope of Angular the data object, without actually parsing it.
The result is that Angular is not able to understand in the ng-repeat directive what actually {{phone.name}} and {{phone.walltime}} are and the JSON string is shown.
In order to have the ng-repeat directive working as expected, you have to parse first the JSON object, process it (creating for example a custom object and assigning its properties) and then assign it to $scope object.
You could perform the parse using something like
JSON.parse(data);.
Please have a look at this question for further information.
Or even using the Angular's builtin function angular.fromJson(data).
An example could this:
$http.get(url).success(function(data) {
alert(data);
$scope.phones = angular.fromJson(data);
});
};
Test this :
var url = 'http://192.168.59.103/members';
$http.get(url).then(
function(response) {
console.log('success',response)
},
function(data) {
// Handle error here
})

AngularJS factory dependencies

I'm using AngularJS to extract information stored in mongodb. I'm trying to use a factory to retrieve that information using $http . I read so much information about how to do it, and no one works for me.
Also I'm using node + express, the routes works fine. The problem is the factory and the dependencies.
The only thing I need is:
Extract information stored in mongodb.
Store that information in a controller.
Show that information in the main page of my app.
index.html
<!doctype html>
<html ng-app="angular-blog">
<head>
<title> Angular blog </title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- AngularJS and JQuery include. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<!-- Custom CSS -->
<link rel="stylesheet" href="./css/article.css" ></link>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"></link>
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"></link>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<menu-bar></menu-bar>
<div class="container" ng-controller="ArticleController as articleCtrl">
<h2> Blog </h2>
<div class="col-sm-4" ng-repeat="elem in articleCtrl.list">
<h4>{{ elem.title }}</h4>
<p> {{ elem.desc }} </p>
</div>
</div>
<!-- Custom controller. -->
<script src="./js/controllers/article.js"></script>
</body>
</html>
article.js
(function (){
var app = angular.module ('angular-blog', []);
app.directive ('menuBar', function (){
return {
restrict : 'E',
templateUrl : '../templates/menu-bar.html'
};
});
app.service ('articleFactory', ['$q', '$http', function ($q, $http){
this.getAllArticles = function (){
var deferred = $q.defer(),
httpPromise = $http.get ('/entries');
httpPromise.success (function (data){
deferred.resolve (data);
})
.error (function (err){
console.log (err);
});
return deferred.promise;
}
}]);
app.controller ('ArticleController', ['$http', 'articleFactory', function ($http, articleFactory){
this.article = {}; // Simple article.
this.list = []; // Article list.
this.list = articleFactory.getAllArticles()
.then (function (data){
return data;
}, function (err){
console.error (err);
});
this.addArticle = function (){
$http.post ('/addEntry', this.article)
.success (function (data){
console.log (data);
})
.error (function (data){
console.log ('Error: ' + data);
});
this.article = {};
};
this.resetArticle = function (){
this.article = {};
};
}]);
})();
Error
My main page doesn't show the list.
DOCS
Change your factory to service as you are using this factory return an object or primitive type not bind with this
app.services('articleFactory', ['$q', '$http', function ($q, $http){
this.getAllArticles = function (){
var deferred = $q.defer(),
httpPromise = $http.get ('/entries');
httpPromise.success (function (data){
deferred.resolve (data);
})
.error (function (err){
console.log (err);
});
return deferred.promise;
}
}]);
UPDATED ANSWER
Your controller should be like this:-
app.controller ('ArticleController', ['$http', 'articleFactory', function ($http, articleFactory){
this.article = {}; // Simple article.
this.list = []; // Article list.
articleFactory.getAllArticles()
.then (function (data){
this.list = data;
}, function (err){
console.error (err);
});
this.addArticle = function (){
$http.post ('/addEntry', this.article)
.success (function (data){
console.log (data);
})
.error (function (data){
console.log ('Error: ' + data);
});
this.article = {};
};
this.resetArticle = function (){
this.article = {};
};

AngularJS $http.get example

I try to get into angularJS's http.get
I have a simple restful service.
http://groupify-webtechproject.rhcloud.com/api/test/helloworld
will return a "Hello World" plain text.
I want to retrieve that with angularjs and and alert it or even better display it on my index.html
But after 2 hours of trying and not getting a step closer maybe one of you can help.
These are my HTML5 and js code snippets:
angular.module('myApp', []).controller('Hello', function ($scope, $http) {
$http.jsonp('http://groupify-webtechproject.rhcloud.com/api/test/helloworld').
success(function(data) {
alert("success");
alert(data);
$scope.data = data;
alert(data);
}).
error(function(data, status) {
alert("error");
alert(data);
});
});
<!doctype html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular-resource.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>{{data}}</p>
</div>
</body>
</html>
you embedded agular 1.* instead of a newer version. also your resource is not available anymore (404).
other than that, the code works.
angular.module('myApp', []).controller('Hello', function ($scope, $http) {
$http.jsonp('http://groupify-webtechproject.rhcloud.com/api/test/helloworld').
success(function(data) {
console.log('success', data);
$scope.data = data;
}).
error(function(data, status) {
console.log('error', data, status);
$scope.data = 'error with status code: ' + status;
});
});
<!doctype html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-resource.min.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>{{data}}</p>
</div>
</body>
</html>

Categories

Resources