I'm just learning Angular JS.
I'm trying to populate the scope variable with the result of an ajax database call.
The ajax call returns a propper json object(an array) but I cannot get $scope.contentType to output on my HTML page.
Can anyone see any reason this should not work?
app.controller('MainController', ['$scope', function($scope){
var allMyData;
$scope.title = 'Content Types List';
var request = $.ajax({
type: "POST",
dataType: "json",
url: "/angularJS/dbServices.cfc?method=getContentTypes"
})
request.done(function(data){
allMyData = data.DATA;
console.log(allMyData);
$scope.contentTypes = allMyData;
})
request.fail(function(){
console.log('fail');
})
}])
The reason your $scope isn't updating on the view is because you are changing that value outside the $digest cycle. You need to use AngularJS' built-in $http service.
You can get more information/documentation in the link above.
It is because you are using jQuery ajax which is not triggering angular digest. You can fix it with:
request.done(function(data){
$scope.apply(function() {
allMyData = data.DATA;
console.log(allMyData);
$scope.contentTypes = allMyData;
})
})
However, this is not the best practice. Instead you should 1) use $http service as mentioned in other answer 2) Move the entire logic to a separate service 3) use a high-level interface provided by ngResource
Related
I have searched and seen many solutions but yet I still am not getting any progress. I get no errors within the console and get nothing in return from the ajax request.
Here is action method code:
[HttpGet]
public ActionResult GetEmployees()
{
AWEmployeeModel aw = new AWEmployeeModel();
aw.ID = 0;
aw.Name = "Selena";
aw.Position = "Cashier";
aw.Department = "Finance";
return Json(aw,JsonRequestBehavior.AllowGet);
}
And here is my ajax call within my controller:
EmpApp.controller("AWEmpControl", function ($scope) {
loadEmployees();
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.employees = response["Name"];
}
});
}
});
I do also have the ng directives on the desired page:
<div class="container" ng-app="AWEmpApp" ng-controller="AWEmpControl">
{{employees}}
</div>
I tested to see if the scripts work fine by assigning $scope.employees = "Hello..."; and no problems, so I know it has nothing to do with script loading.... What could be the issue? I've made sure to describe the request as GET and to return a JSON object. Am I missing something?
Thanks in advance.
EDIT
I checked the firefox console and got back Parsing Error: No XML found at location.......
Which I found odd since the server returns a JSON object, so I replaced the ajax method with the following:
function loadEmployees() {
$http.get('/AWEmployee/Index/GetEmployees')
.then(function(response) {
$scope.employees =response;
});
};
Now response is html data of the page that called it (Index), instead of the JSON object ! I assume something is happening in between the communication as suggested in this post.
As you use JQuery to fetch data from server instead of $http service and moreover success function is executed asynchronous, AngularJS will not reflect any changes that was happened, to force it, just wrap assigning into $apply:
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.$apply(function(){
$scope.employees = response["Name"];
});
}
});
}
Found out the issue, it's a simple mistake on my part. I was calling http://localhost:53729/AWEmployees/Index/GetEmployees which was the wrong thing to do. I took out the Index page, so now the url looks like http://localhost:53729/AWEmployees/GetEmployees and it worked perfectly!
I'm building my first little AngularJS app.
I'm successfully able to show all entries from the API on the home page of the app.
Then I'm routing the user via ng-href to /jobs/{{job.id}} and have the appropriate controller to do that.
My console.log statement is telling me that the correct entry is being loaded via the GET request method but the template isn't actually pulling that back for display.
Here's the extent of what I have so far http://plnkr.co/QPW3lsLHfPxyYOKcVOKY (obviously my API isn't public) but wondering if there's something obvious I'm missing in my show template relating to the showController perhaps?
I've been working along with CodeSchool but I've had to make some mods to their code (for example the showController wasn't correctly defining $http or $routeParams).
Help appreciated.
So it seems there's an issue between the tutorial version of Angular 1.3.x and the one I'm using 1.4.x
However, using this works as sweet as a nut, passing $scope as a function parameter
angular.module('JobStore')
.controller('JobsShowController', function($http, $routeParams, $scope) {
$http({
method: 'GET',
url: '/jobs/' + $routeParams.id + '.json'
}).success(function(data) {
$scope.job = data;
console.log(data);
});
})
I am working on a school project and have run into trouble. Namely, I am building a simple AngularJS app which shows some kind of a radio chart based on Last.FM's data.
However, when trying to access the API, I never get a response.
This is the code that I use for accessing:
APIservice.getChartTracks = function () {
return $http({
method: 'JSONP',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json'
});
}
Afterwards, when I do something like this:
APIservice.getChartTracks().success(function (response) {
$scope.tracks = response.tracks.track;
});
the success() method never gets called. If I were to change the url to this one (found it on some online tutorial), I get a response and everything.
How should I go about accessing Last.FM's API?
Thanks in advance.
With $http, the method to use is GET, not JSONP. Write:
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json'
});
Or use the shortcut:
return $http.get('http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json');
I am trying to send and then get data from PHP on my server, but I don't think it sends the data.
My js code:
angular
.module('h2hApp', [])
.controller('mainCtrl', ['$scope', '$http', function(scope, http) {
scope.initGames = function() {
http({
method: 'POST',
url: 'apis.php',
data: {
url: someUrl
}
})
.success(function(data) {
console.log(data);
});
};
scope.initGames();
}]);
and my PHP file:
<?php
$url = $_POST['url'];
echo file_get_contents($url);
?>
The only thing I get in response is that error:
Notice: Undefined index: url in /my/path/apis.php on line 2
I made this working using jQuery but with AngularJS it doesn't seem to work. I'm new to Angular and I read some other problems like this. I tried things like adding headers and other things but nothing worked.
You can be forgiven for thinking that your PHP script should be expecting data in the $_POST variable as encoding your data as a query string has traditionally always been the default mechanism.
Angular however encodes the message body as a JSON object by default. As mentioned you could use the params instead however in the long run I'd argue that it's more flexible to conform on the server-side. For example you can read and decode the message body as follows:
<?php
$data = json_decode( file_get_contents('php://input') );
echo $data->url;
It should be 'params', not 'data'. See http://docs.angularjs.org/api/ng/service/$http#usage
Be sure to set the HTTP header, sort of like this:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
More info on using Post from AngularJS to PHP
You can use http.post() method -
Try this the code -
http.post('apis.php', {
url: someUrl
})
.success(function(data) {
console.log(data);
});
I am using angular's $http.jsonp() request which is successfully returning json wrapped in a function:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";
$http.jsonp(url).
success(function(data, status, headers, config) {
//what do I do here?
}).
error(function(data, status, headers, config) {
$scope.error = true;
});
How to access/parse the returned function-wrapped-JSON?
UPDATE: since Angular 1.6
You can no longer use the JSON_CALLBACK string as a placeholder for
specifying where the callback parameter value should go
You must now define the callback like so:
$http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
Change/access/declare param via $http.defaults.jsonpCallbackParam, defaults to callback
Note: You must also make sure your URL is added to the trusted/whitelist:
$sceDelegateProvider.resourceUrlWhitelist
or explicitly trusted via:
$sce.trustAsResourceUrl(url)
success/error were deprecated.
The $http legacy promise methods success and error have been deprecated and will be removed in v1.6.0. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
USE:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
var trustedUrl = $sce.trustAsResourceUrl(url);
$http.jsonp(trustedUrl, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});
Previous Answer: Angular 1.5.x and before
All you should have to do is change callback=jsonp_callback to callback=JSON_CALLBACK like so:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
And then your .success function should fire like you have it if the return was successful.
Doing it this way keeps you from having to dirty up the global space. This is documented in the AngularJS documentation here.
Updated Matt Ball's fiddle to use this method: http://jsfiddle.net/subhaze/a4Rc2/114/
Full example:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
});
The MOST IMPORTANT THING I didn't understand for quite awhile is that the request MUST contain "callback=JSON_CALLBACK", because AngularJS modifies the request url, substituting a unique identifier for "JSON_CALLBACK". The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK":
JSON_CALLBACK(json_response); // wrong!
Since I was writing my own PHP server script, I thought I knew what function name it wanted and didn't need to pass "callback=JSON_CALLBACK" in the request. Big mistake!
AngularJS replaces "JSON_CALLBACK" in the request with a unique function name (like "callback=angular.callbacks._0"), and the server response must return that value:
angular.callbacks._0(json_response);
This was very helpful. Angular doesn't work exactly like JQuery. It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. Here's an example:
var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
$http.jsonp('http://librivox.org/api/feed/audiobooks/author/Melville?format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
Then display or manipulate {{ data }} in your Angular template.
This should work just fine for you, so long as the function jsonp_callback is visible in the global scope:
function jsonp_callback(data) {
// returning from async callbacks is (generally) meaningless
console.log(data.found);
}
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";
$http.jsonp(url);
Full demo: http://jsfiddle.net/mattball/a4Rc2/ (disclaimer: I've never written any AngularJS code before)
You still need to set callback in the params:
var params = {
'a': b,
'token_auth': TOKEN,
'callback': 'functionName'
};
$sce.trustAsResourceUrl(url);
$http.jsonp(url, {
params: params
});
Where 'functionName' is a stringified reference to globally defined function. You can define it outside of your angular script and then redefine it in your module.
For parsing do this-
$http.jsonp(url).
success(function(data, status, headers, config) {
//what do I do here?
$scope.data=data;
}).
Or you can use
`$scope.data=JSON.Stringify(data);
In Angular template you can use it as
{{data}}
for me the above solutions worked only once i added "format=jsonp" to the request parameters.
I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
url = $sce.trustAsResourceUrl(url);
$http.jsonp(url, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});