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>
Related
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>
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.
I'm trying to use several AngularJS's ajax call to call a single php file to get different json data accordingly, below is my code:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $http) {
$http.get('myphp.php',{key: "main1"}).then(function (response){
console.log(response);
//do something
});
$http.get('myphp.php',{key: "main2"}).then(function (response){
//do something
});
});
<html ng-app="myApp">
<header>
<!-- AngularJS-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</header>
<body>
<div ng-controller="MyController">
<div id="main1">
</div>
<div id="main2">
</div>
</div>
</body>
</html>
In myphp.php file I have:
<?php
if (isset($_GET["key"])) {
if ($_GET["key"]=="main1") {
$url1 = 'http://www.w3schools.com/angular/customers.php';
$content = file_get_contents($url1);
echo $content;
}
else if ($_GET["key"]=="main2") {
$url2 = "blabla"
$content2 = file_get_contents($url2);
echo $content2;
}
}
?>
As you can see, I'm trying to differentiated different ajax calls and try to get correct data from the counterpart ajax call from php by sending a value while calling myphp.php.
The problem is,,,,it won't work, I'm guessing that my syntax is messed up, can you guys help? Thank you so much in advance!
This is the result I got:
I add "var_dump($_GET);" at the top of my php code and this is what I got.
You have some errors in html and angular logic.
In html you declare your ng-app directive before load angular core
<html >
<header>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
</header>
<body ng-app="myApp">
<div ng-controller="MyController">
<button ng-click="getContent('main1')"> main1</button>
<button ng-click="getContent('main2')"> main2</button>
<pre>{{content | json}}</pre>
</div>
</body>
</html>
we already saw the logic errors in php :)
<?php
if (isset($_GET["key"])) {
if ($_GET["key"]=="main1")
$url = 'http://www.w3schools.com/angular/customers.php';
else if ($_GET["key"]=="main2")
$url = "https://www.google.com";
$content = file_get_contents($url);
echo $content;
}
?>
in angular you call twice the $httpservice without correct parameters.
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $http) {
$scope.getContent = function(key){
$http.get('myphp.php',{params: {key: key}}).then(function (response){
$scope.content = response.data;
});
}
});
Nevermind folks, I solved it. The syntax is wrong, it should be
$http.get(url, {
params: { param1: value1, param2:value2, param3:value3...... }
});
please refer to :
http://tutorialsplane.com/angularjs-pass-data-to-http-get-request/
<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
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 = {};
};