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

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>

Related

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.

How to use AngularJS's several ajax call($http) to request data from a single php file?

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/

Fetching JSONP with Angular.js

<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

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 $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