I am new to angularJs. I am trying to get dJango rest api data from angularJs. Using jsonp method, data is fetching from api (showing in chrome browser sources tab). But it is not showing in html page. Please check below code.
var myApp = angular.module('myApp',[]);
var dataController = function ($scope, $http, $window, $sce) {
var url = 'http://myIpWithPort/ids/?callback=JSON_CALLBACK';
$sce.trustAsResourceUrl(url);
$http.jsonp(url,{ jsonpCallbackParam: 'callback' }).then(function (data) {
$scope.emps = JSON.parse(data.data);
})
}
myApp.controller('dataController', dataController);
<div ng-controller="dataController">
<div>{{ emps }}</div>
</div>
Any one please help me.
since you are using jsonp method you do not need to parse the data to json again.just assign the values
$scope.emps =data.data
Related
I am very new to Angular JS and the Ionic application. I have tried to fetch the json data from the url . But, unfortunately I could not get any response. Instead, I get the error as shown in the screen below
I have tried in two ways,
Try 1:
function(){
return $http.get("url?subjStudyId=441",{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}).then(function(response){
chats = response.data;
alert(JSON.stringify(chats));
return chats;
},function(err) {
alert(JSON.stringify(err));
})
}
Try 2:
function($http) {
var chats = [];
return {
all: function(){
return $http.get("url?subjStudyId=441").then(function(response){
chats = response.data;
alert(JSON.stringify(chats));
return chats;
},function(err) {
alert(JSON.stringify(err));
})
}
}
Please help me finding the solution .
Your problem may be CORS which stands for Cross-Origin Resource Sharing take a look at this in-depth CORS article here.
Enable CORS on your backend and try to do the request again. You can also make use of JSONP by enabling that on the backend then doing
$http.jsonp('url?callback=JSON_CALLBACK¶m=value);
JSONP stands for "JSON with Padding" (and JSON stands for JavaScript
Object Notation), is a way to get data from another domain that
bypasses CORS (Cross Origin Resource Sharing) rules. CORS is a set of
"rules," about transferring data between sites that have a different
domain name from the client.
I coded up two examples, one using $http.get and the other $http.jsonp, neither work which tells me that you don't have Access-Control-Allow-Origin "*" in your server nor do you have JSONP support setup. Head over to enable-cors.org, they got nice articles to help you get CORS setup on your backend.
Technically, you should stick to CORS, since JSONP is more of a security concern. So if nothing is stopping you from just enabling CORS then stick to that.
Example of doing a standard $http.get and $http.jsonp requests via the use of promises.
var app = angular.module("MyApp", []);
app.controller("MyCtrl", function($scope, $http){
$scope.data = "";
$scope.normalCall = function(){
var results = $http.get('http://202.133.56.91:8081/SD_BIO/app/retrievenotifications.action?subjStudyId=441')
.then(function(response){
$scope.data = response;
}, function(error){
$scope.data = error;
});
return results;
};
$scope.jsonPCall = function(){
var results =$http.jsonp("http://202.133.56.91:8081/SD_BIO/app/retrievenotifications.action?callback=JSON_CALLBACK")
.then(function(response){
$scope.data = response;
}, function(error){
$scope.data = error;
});
return results;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<button ng-click="normalCall()">Original Call</button> |
<button ng-click="jsonPCall()">JSONP Call</button>
<br><br>
<div ng-model="data">{{data}}</div>
</div>
</div>
You need to specify the url you are going to do the GET
url?subjStudyId=441
isn't a url, it needs to be something like -> someurl.com/?subjStudyId=441 where the -> ? is the query start and the -> = is the value you are
Well, i'm having some difficult to understand the use of angular.toJson. I completely understand that it changes to a json object...
But, how can i send this obj to the server ?
The server already gives a json obj when 'GET', but how use it to 'POST' and others?
sorry, i'm new :)
You can create factory in your app:
var app = angular.module('myApp', []);
app.factory('requestsFactory', ['$http', function ($http) {
return {
postData: function (data) {
var url = // some url to send your data
return $http.post(data, url);
};
};
}];
And now, you can post your data from controllers:
app.controller('yourController', ['$scope', 'requestsFactory', function ($scope, requestsFactory) {
...
requestFactory.postData(anyData).success(function (result) {
// if server send any response
}
...
}]);
Also you can use $http for GET, PUT, DELETE requests. Click here for more information
You don't actually need to call angular.toJson() yourself when posting data to a server or retrieving data from the server using the $http service.
This is the default behaviour that Angular does for you.
From the docs:
Angular provides the following default transformations:
Request transformations ($httpProvider.defaults.transformRequest and
$http.defaults.transformRequest):
If the data property of the request configuration object contains an
object, serialize it into JSON format.
Response transformations
($httpProvider.defaults.transformResponse and
$http.defaults.transformResponse):
If XSRF prefix is detected, strip it (see Security Considerations
section below).
If JSON response is detected, deserialize it using a
JSON parser.
Good afternoon! Learning Angularjs. Below is the structure of the project.
I have a service that reads data from json
var WebKrServices = angular.module('WebKrServices', ['ngResource']);
WebKrServices.factory('DataPlant', ['$resource',
function($resource){
return $resource('plants/:plantId.json', {}, {
query: {method:'GET', params:{plantId:'plants'}, isArray:true}
});
}]);
And Controller
var WebKrControllers = angular.module('WebKrControllers', []);
WebKrControllers.controller('PlantsCtrl', ['$scope', 'DataPlant',
function($scope, DataPlant) {
$scope.plants = DataPlant.query();
}]);
which transmits this information to the html
<div ng-repeat="plant in plants">
<h2 class="text-center">{{plant.name}}</h2>
</div>
And, in fact question. In html I see data from json, and the controller when accessing the plants I see an empty object?
for (var p in plants) {
. . .
}
How to get data from the plants in the controller?
Thank you all for your answers.
Cause it is asynchronous call. After $scope.plants = DataPlant.query();, plants remain undefined until data arrives (Well, it is not exactly undefined, you can inspect it in debugger). When data arrives - $scope.plants get resolved and html is updated. To run some code after data arrives, use callbacks:
$scope.plants = DataPlant.query(function(response) {
console.log($scope.plants);
}, function (response) {
console.log('Error');
});
I have the following code to present data from a link (API) as suggestion for an autocomplete box. Although it is working for one link and not the other. I observed that data format for both are different, modified my code accordingly but it is still not helpful.
.js file:
var plunker= angular.module('plunker', ['ui.bootstrap', 'ngGrid']);
function TypeaheadCtrl($scope, $window, $http, limitToFilter) {
$scope.cities = function (cityName) {
return $http.jsonp("http://mtapi.azurewebsites.net/api/institute").then(function (response) {
return response[0].description;
});
};
}
HTML file:
<input type="text" id="depn" ng-model="formdata.department"
typeahead="suggestion.description for suggestion in cities($viewValue)"
placeholder="department" class="form-control">
If you replace the cities function with this one,
$scope.cities = function (cityName) {
return $http.jsonp("http://gd.geobytes.com/AutoCompleteCity?callback=JSON_CALLBACK &filter=US&q=" + cityName).then(function (response) {
return response.data;
});
};``
Even after I changed my code jsonP request to .get, it is still not working
var plunker= angular.module('plunker', ['ui.bootstrap', 'ngGrid']);
function TypeaheadCtrl($scope, $window, $http, limitToFilter) {
$scope.cities = function (cityName) {
return $http.get("http://mtapi.azurewebsites.net/api/institute").success(function(data) {
return data[0].description;
});
};
}
It is working fine.
Is there a problem with my code, or a back end server issue?
Change your cities function to use the data property of the response in your .then (that's how you'll access the response from a resolved HttpPromise):
var plunker= angular.module('plunker', ['ui.bootstrap', 'ngGrid']);
function TypeaheadCtrl($scope, $window, $http, limitToFilter) {
$scope.cities = function (cityName) {
return $http.get("http://mtapi.azurewebsites.net/api/institute").then(function (response) {
return response.data[0].description;
});
};
EDIT
Even making that code change won't solve your problem. This url does not support cross-origin requests, so you either need to host your angularjs app on the same domain and use a plain $http.get instead of $http.jsonp, or this url needs to support JSONP requests (the content-type of the response from this url is application/json. For JSONP to work it should be application/javascript).
I figured it out lately. Apart from the problem at back end there were issues in this code as well. I was returning the promise, but promise was never resolved to return the value also I was trying to return a string, whereas I should return array of strings. Here's the change:
$scope.aap = result.data;
var res = [];
res.push($scope.aap[0].Description);
return res;
I am trying to learn how to load JSON with Angular. I'm a beginner with both topics, and am stuck on some really beginner topics.
I have a JSON file called food.json. It has structure like this:
[
{"uid":"55","title":"Nussbrot","code":"U VP 0000030","unit":[{"title":""}],"unitgram":"0","unitgram_second":"0","sorting":"0"},
{"uid":"58","title":"Walnu\u00dfbrot","code":"X 39 2000002","unit":[{"title":"Scheiben"}],"unitgram":"45","unitgram_second":"0","sorting":"0"}
]
Following instructions from http://toddmotto.com/ultimate-guide-to-learning-angular-js-in-one-day/, I have a controller like this:
myApp.controller('EmailsCtrl', ['$scope', function ($scope) {
$scope.foodlist = {};
$scope.foodlist.foodtitle = '';
$http({
method: 'GET',
url: 'food.json'
})
.success(function (data, status, headers, config) {
$scope.foodlist = data.; //I don't know what to call here as my data elements have no names?
})
.error(function (data, status, headers, config) {
//error
});
}]);
The first point I am stuck in is, how do I assign data to my ´$scope.foodlist´ if the JSON objects have no names?
I've built a Plunkr of my not-working attempts so far, and would appreciate any guidance in a) reading in the JSON and b) assigning the JSON data to values in controller.
ng-repeat in your case will iterate the array of objects in your data
You just need to use :
<li ng-repeat="food in foodlist">
Then on each pass of the loop, angular will reference the current object in array to produce output like {{ food.title }}
I updated your demo here
Edit Strongly suggest you go through the tutorial on angular docs site step by step
The first problem is in the controller definition: You are trying to reference $http but you are not passing it in.
myApp.controller('EmailsCtrl', ['$scope', '$http', function ($scope, $http) {
Then on success your data parameter is your foodlist:
.success(function (data, status, headers, config) { $scope.foodlist = data; })
Finally, in your html, ng-repeat should be like this:
ng-repeat="food in foodlist"