Angular.js reading External JSON Address - json

Hey guys I am trying to use an EPA API that provides daily UV Index information in JSON.
The link I am trying to read at the moment is:
http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/33126/JSON?callback=callBackFn
If you open that link it shows valid JSON, but when I use it in my Angular.js code it does not read it, and my variable stays as unknown. My code is:
var tanApp = angular.module('tanApp')
.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.data = 'unknown';
$http.get('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/33126/JSON?callback=callBackFn').success(function(data){
$scope.data = data;
});
tanApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
My HTML code is {{data}}.
When I take out the "JSON" portion, it comes up as XML, since it is the default, and that is actually showing up, but I need it as JSON.
Can someone possibly get this to work or provide some help? I can offer bitcoin as a bounty.
Thanks!

The problem is that the URI you're using returns raw JSON instead of JSONP. You can either setup a server-side proxy or check with your API provider to see if there's a way to get a valid JSONP response.
If you can get valid JSONP, you will also have to setup a callback to handle the response.
In that case, reference the accepted answer for this question.

Have you tried this using $http.jsonp() instead of $http.get(). Also if your using $http.jsonp() then the callback should be set to "JSON_CALLBACK".
e.g.
$http.jsonp('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/33126/JSON?callback=JSON_CALLBACK')
.success(function(data){
$scope.data = data;
}

Related

Ajax call in AngularJS not getting data from JSON file [duplicate]

The AngularJS documentation has a Deprecation Notice for the $http success and error methods. Is there a specific reason this abstraction was removed from the library?
The problem was that .success and .error methods are not chainable because they ignore return values. This caused problems for people familiar with chaining and encouraged poor code from people unfamiliar with chaining. Witness all the examples on StackOverflow that use the deferred anti-pattern.
To quote one of the AngularJS team:
IMO .success and .error were a bad bit of API design in the first place. This issue highlights a number of situations where developers get confused because they either expect .success and .error to work the same way as .then or vice versa.
In a perfect world I would rather just ditch these $http specific "promises". Instead we could encourage developers to use the standard $q promise API .then and .catch. There is very little benefit IMO in working with explicit parameters over working with the response object.
— AngularJS Issue #10508 $http .success/.error dissimilar from how .then works.
Deprecation Notice (v1.5)
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
— AngularJS $http Service API Reference -- deprecation notice
UPDATE
The deprecated .success and .error methods have been removed from AngularJS 1.6.
Due to b54a39, $http's deprecated custom callback methods - .success() and .error() - have been removed. You can use the standard .then()/.catch() promise methods instead, but note that the method signatures and return values are different.
$http(...)
.then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
}).catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
});
— AngularJS Developer Guide - Migrating to v1.6 - http
The pattern that javascript it using related to promises is only with .then(successCallback, errorCallback), so they are probably aiming to use js pattern.

Angular $http not working as expected

I am new to angular and trying to consume a basic back end service that I created using laravel. It is a basic Todo application and I am trying to fetch all the users resource for now.
If you go to the following URI, it will give back the all the users in the application:
Link to the URI
The code in my angular file looks like
var testing = angular.module('testing', []);
testing.controller('MainCtrl', function($scope, $http){
$scope.hello = "Hello World!";
$http.get('users.json').success(function(data){
$scope.users = data;
});
});
Now when I pass the URI in the parameter of $http.get method, I don't see any data. I have tried {{ users | json }} in my main index file to see the dump output. It simply doesn't work. But when I copy just the data array in the response and save it to a json file, it works perfectly.
Now the json that is returned from the web service has slightly more information like status and messages. How do I remove them when fetching them in Angular so that it works or is there a way I can have them returned and then extract them somehow from the whole data that has been returned?
If here http://todoapi.rohanchhabra.in/users is response from your server you should update your $http call to :
$http.get('users.json').success(function(response){
$scope.users = response.data;
});
if you requesting json file from your local iis make sure that it can serve .json files

AngularJS - access elements in scope

I have done a service that gets a json file from the server with the translated values of the labels of my webapp. Seems to work fine:
mobilityApp.service('serveiTraduccions', function($resource) {
this.getTranslation = function($scope) {
var languageFilePath = 'traduccions/traduccio_en.json';
$resource(languageFilePath).get(function (data) {
$scope.translation = data;
});
};
});
What I am trying to do is acces that "$scope.translation" from my controler, I tried all and nothing worked. The object is saved in my $scope as you can see:
how can I get the values of the "registroBtnRegistro", "registroErrorRegistro" etc ?
Thanks in advance !
I tried:
console.log($scope.translation); -> undefined
console.log($scope['translation']); -> undefined
console.log($scope.translation.registroBtnRegistro); -> TypeError:
Cannot read property 'registroBtnRegistro' of undefined
console.log($scope.translation['registroBtnRegistro']); -> TypeError:
Cannot read property 'registroBtnRegistro' of undefined
Maybe you're trying to access these values from another $scope that not inherits the scope where you've created your translation model.
Try to assign this model directly to $rootScope, so you can access it from every scope:
mobilityApp.service('serveiTraduccions', function($resource, $rootScope) {
this.getTranslation = function() {
var languageFilePath = 'traduccions/traduccio_en.json';
$resource(languageFilePath).get(function (data) {
$rootScope.translation = data;
});
};
});
this answer is a blind attempt because your original post lacks basic information like the call from the controller.
we can refine it until we make it work.
First, you should be returning something from your method:
mobilityApp.service('serveiTraduccions', function($resource) {
this.getTranslation = function() {
var languageFilePath = 'traduccions/traduccio_en.json';
return $resource(languageFilePath);
};
});
You are using $resource but you might as well use basic $http.get(). at least it doesn't look like a restful api to me.
In any case, because it's an asynchronous request, it will not return the list of translated strings, but a resource "class" that allows methods like get, delete or the more general query():
from the docs: default methods are
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
sidenote: injecting $scope in a service doesn't make much sense to me: services are used to encapsulate common logic accross components. However, you can pass a scope instance as a parameter.
Then, the controller that uses this should have the service injected and use a callback to get the results when they have arrived (asynchronous operation!):
TraduccioCtrl ... {
$scope.translation = {}; // avoid undefined when the view just loads
ServeiTraduccions.getTranslation.query(function (response) {
$scope.translation = response; // and angular's two-way data binding will probably do the rest
});
}
The Angular docs about ng-resource have a working example. Other questions in SO have addressed this already too, like Using AngularJS $resource to get data

How to see what JSON returns in my view

Can some one help or explain to me how this works please?
i have in my view:
<script type="text/javascript">
var jqxhr = $.getJSON("<%= Url.Action("GetTrainingModulePoints" , "Home") %>", function (json) {
console.log(json);
});
</script>
GetTrainingModulePoints should return 4 rows each containing a value for interactiontype and a value for points
in the console log i just get [object object]?
how can i see what is in the variable json?
http://imageshack.us/photo/my-images/542/firebug.png/
thanks
Look at the Network tab in FireBug or similar javascript debugging tool. There you will see the AJAX request and all you have to do is expand the request and look at the response.
Here's for example how that might look like in FireBug for a sample AJAX request:
And if you click on the JSON tab you will see the output formatted as a JSON object where you could expand/collapse the properties.
If for some very weird reason you cannot use a javascript debugging tool in your web browser (I don't know even know how you could be developing a web application, but ...) you could use the JSON.stringify method that's built into modern browsers:
var jqxhr = $.getJSON("<%= Url.Action("GetTrainingModulePoints" , "Home") %>", function (json) {
alert(JSON.stringify(json));
});
And if you are not using a modern browser which doesn't have the JSON.stringify method natively built-in you could still reference the json2.js script to your page.
UPDATE:
OK, it seems that your confusion comes from the fact that you are getting {"success":true} whereas you were expecting to get the rows from your stored procedure. I know this because I answered your previous question.
Here's how your controller action look like:
[HttpGet]
public JsonResult GetTrainingModulePoints()
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.TrainingService.GetTrainingModulePoints(currentUser.UserId);
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
As you can see in this controller action you are always returning success = true. If you want to return the results from your stored procedure you could do this:
[HttpGet]
public JsonResult GetTrainingModulePoints()
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
var modulePoints = ZincService.TrainingService.GetTrainingModulePoints(currentUser.UserId);
return Json(
new {
success = true,
modulePoints = modulePoints
},
JsonRequestBehavior.AllowGet
);
}
Here I assume that your TrainingService.GetTrainingModulePoints method is actually returning some object. If this is not the case you will have to explain what those methods are doing and how do you expect to get the output.

How do I get the cookie values in a backbone.js model?

I have a simple Backbone.js/Bootstrap front end in HTML5 with a Node.js/Restify backend. I am setting cookies in a header response from the server as below:
res.setHeader("Set-Cookie", ["token=ninja", "language=javascript"]);
On the client side, I am making a REST call as
var response = this.model.fetch().success(function(data){
//success
}).error(function(data){
//error
}).complete(function(data){
//complete
});
that callsback a parse method in the model.
How can I read the cookie value in the model?
Include Cookie.js.
You can then reference individual cookies like this:
var token = Cookie.get('token')
# token == 'ninja'
Here is what I figured out. My application has two components - the HTML/js from one domain that talks to a REST sevice on another domain (and therefore is cross-domain.) Because the cookie is set from REST, it appears is not readable across domains. So the web page will not store the cookie even though the server is sending it. One alternative is to use local cookies or use the technique illustrated by http://backbonetutorials.com/cross-domain-sessions/.
Assuming you are using jQuery with Backbone, you can get the headers by defining the parse function in your model by calling getAllResponseHeaders or getResponseHeader:
var model = Backbone.Model.extend({
// the rest of your model
parse: function(resp, xhr) {
var allHeaders = xhr. getAllResponseHeaders();
var cookieHeader = xhr. getResponseHeader("Set-Cookie");
// do something with the headers
return resp;
}
});