How to access ajax response data outside ajax function in angularjs - angularjs

I am fetching some data via http get ajax.
$.ajax({
type: "GET",
url: "/userdata/",
success: function(response){
$scope.steps = response.no_of_steps;
$scope.calories = response.calories;
},
error: function(){
alert("error");
}
});
If i print it on console from inside the success function, it prints the value like:
success: function(response){
var $scope.steps = response.no_of_steps;
var $scope.calories = response.calories;
console.log($scope.steps, $scope.calories);
},
But if i print it on colsole outside my ajax request, it print undefined. how is that so?
$.ajax({
...
});
console.log($scope.steps, $scope.calories);

this is continuation of my comment on your post above
you could do that by using $scope.$emit("custom-event-name"); of angular,
here you are actually watching $scope.steps and $scope.calories for change once your ajax call completes signify this by using $emit of angular
and then listen for that event by $scope.$on("custom-event-name", function(){})
and log it there, Please do make sure your "custom-event-name" is same in $emit and $on
in success callback : initialize the value and use $emit to emit an event named initialized as :-
$scope.steps = response.no_of_steps;
$scope.calories = response.calories;
$scope.$emit("initialized");
and then listen for that event initialized
$scope.$on('initialized', function () {
console.log($scope.steps + ' and ' + $scope.calories);
});

Couple of mistakes here.... use $http instead of $ajax, secondly you are defining your variables inside your success function so the scope is limited once it comes out of it... define your function globally in your controller and then access it inside your success function.
var $scope.steps => wrong way
$scope.steps = "something"; => right way.
You don't need to append var keyword with $scope in angularjs.
$scope.steps;
$scope.calories;
$.ajax({
type: "GET",
url: "/userdata/",
success: function(response){
$scope.steps = response.no_of_steps;
$scope.calories = response.calories;
},
error: function(){
alert("error");
}
});
Use $scope variables if you want to bind to the view and var does not and is local to the function it was declared in.

This works for me, i want to recommend you not to make use of $.ajax in angular js its a jquery function; i heard $http is faster than $.ajax function.
Hope this works for you if didnot work please inform me
//$scope.tablerows defined outside the function
$scope.tablerows;
module='user';
url=siteurl+"/admin/"+module+"/list";
BlockUi();
// $http is ajax call in angular js which is equivalent to $.ajax();
$http({
url : url,
method : "GET",
data : "",
headers : { 'Content-Type':undefined,
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
}
//responseText is the output of success call
}).then(function(responseText){
// assigning the response text on the variable
$scope.totaltablerows=responseText.data.response_data;
$scope.tablerows=$scope.totaltablerows;
UnblockUi();
},function(error){
//alert(JSON.stringify(error));
UnblockUi();
UnknownError(JSON.stringify(error));
});

Related

AngularJS access $http on onNotification event PushNotification cordova plugin

I'm using the plugin https://github.com/phonegap-build/PushPlugin/ with Angular 1.3 and I need to send the regid to server when receive "registered" event.
The problem is that I don't have $http object to call my server on this context. How can I achieve that, please?
function onNotification(e){
if(e.event == "registered"){
var req = {
method: "POST",
url: "http://myurl.com/?var="+e.regid
};
$http(req).success(function(data){
alert(data);
});
}
}
I just learned how to inject $http into the event method:
$http = angular.injector(["ng"]).get("$http");
Change $http call as follows, .success is deprecated.
$http({
method: "POST",
url: "http://myurl.com/?var="+e.regid
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
alert(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Ref. : https://docs.angularjs.org/api/ng/service/$http
Regards.

Creating custom header for $http in AngularJs

In my controller i want send a request using get method if $http, in that get method i want to send the sessionID in headers. Below am giving the code snippet please check.
this.surveyList = function () {
//return session;
return $http.get('http://op.1pt.mobi/V3.0/api/Survey/Surveys', {headers: { 'sessionID': $scope.sessionid}})
.then(function(response){
return response.data;
}, function(error){
return error;
});
}
but this is not working when i send this vale in backend they getting null.
So how to resolve this.
we have a issue where the api is getting called twice from angular , however it works only once when called with the POSTMAN. And here with the custom header passed to the api, the action is called twice. What could be the reason for it?
Try in this way,
$http({
method: 'GET',
url: 'http://op.1pt.mobi/V3.0/api/Survey/Surveys',
headers: {
'sessionId': $scope.sessionid
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs,
// or server returns response with an error status.
});

Property on $scope set inside of $http.success() is undefined outside of $http.success(). Why?

I am following an AngularJS tutorial that uses $resource to retrieve JSON data from an API call. For the purpose of understanding, I tried to replace the $resource code with $http code and I encountered a scope problem. Logging $scope.weatherResult outside of .success() results in undefined. Why is that the case? The view receives the data just fine.
Also,
// $scope.weatherAPI = $resource(
'http://api.openweathermap.org/data/2.5/forecast/daily',
{ callback: 'JSON_CALLBACK' }, { get: { method: 'JSONP' }}
);
// $scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 2});
$http.get('
http://api.openweathermap.org/data/2.5/forecast/daily'
+ '?q='
+ $scope.city
+ '&'
+ 'cnt=2'
)
.success(function(data) {
$scope.weatherResult = data;
})
.error(function(error) {
console.log(error);
});
console.log($scope.weatherResult);
Because $http is asynchronous.
$scope.weatherResult is defined only when the http response is available.
See for example http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027, or better, as PSL says: How do I return the response from an asynchronous call?
You can use $watch to be informed:
$watch('weatherResult',function(newValue,oldValue)) {
..
}
When you write
.success(function(data) {
$scope.weatherResult = data;
})
in your program, you are asking the remaining part of your code to continue its execution with a promise.
In this case console.log($scope.weatherResult);
will be executed just after your $http.get() method without waiting for the response from the http request.
Hence, console.log($scope.weatherResult); will be executed even before the API response is received.
Note that $scope.weatherResult is defined inside .success(), so until the response is a success, Angular has no idea about $scope.weatherResult hence the console gives undefined. It will be undefined even in case of an error.
To view the response of server, you can log it well inside success block.
.success(function(data) {
$scope.weatherResult = data;
console.log("$scope.weatherResult = ",$scope.weatherResult);
})

how to make synchronous http request in angular js

How to make blocking http request in AngularJS so that i can use the $http response on very next line?
In the following example, $http object doesn't return the result to the next line so that I can pass this result to fullcalender(), a JavaScript library, because $scope.data returns blank value.
This is the sample code:
$http.get('URL').success(function(data){
$scope.data = data;
});
$.fullCalender({
data: $scope.data
});
You can use promises for that.
here is an example:
$scope.myXhr = function(){
var deferred = $q.defer();
$http({
url: 'ajax.php',
method: 'POST',
data:postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
//if request is successful
.success(function(data,status,headers,config){
//resolve the promise
deferred.resolve('request successful');
})
//if request is not successful
.error(function(data,status,headers,config){
//reject the promise
deferred.reject('ERROR');
});
//return the promise
return deferred.promise;
}
$scope.callXhrAsynchronous = function(){
var myPromise = $scope.myXhr();
// wait until the promise return resolve or eject
//"then" has 2 functions (resolveFunction, rejectFunction)
myPromise.then(function(resolve){
alert(resolve);
}, function(reject){
alert(reject)
});
}
You can't, you'll need deal with it through promises, but you could try do it like this:
$http.get('URL').success(function(data){
angular.copy(data, $scope.data);
});
$.fullCalender({
data: $scope.data
});
but most people would just do
$http.get('URL').success(function(data){
$.fullCalender({
data: data
});
});
If whatever your fullCalender object is doesn't work with async data, you might need to wrap it in something like ng-if or force it to redraw when the data has been supplied. You can also force the controller to not load until the data is loaded by using the route resolve.
Here is a practical answer, courtesy of user Kirill Slatin who posted the answer as a comment. Practical use example at the bottom of the answer.
If, like me, you need to use that response object as a scope variable, this should work:
$http.get('URL').success(function(data){
$scope.data = data;
$.fullCalender = $scope.data;
$scope.$apply()
});
$scope.$apply() is what will persist the response object so you can use that data.
-
Why would you need to do this?
I'd been trying to create an "edit" page for my recipes app.
I needed to populate my form with the selected recipe's data.
After making my GET request, and passing the response data to the $scope.form, I got nothing... $scope.$apply() and Kirill Slatin helped big time. Cheers mate!
Here's the example from my editRecipeController:
$http.get('api/recipe/' + currentRecipeId).then(
function (data) {
$scope.recipe = data.data;
$scope.form = $scope.recipe;
$scope.$apply()
}
);
Hope that helps!

AngularJS $rootScope loses value unless I use promise (trigger.io AJAX request)

So this is quite weird. $rootScope is getting set correctly within a function, but then loses its value. I can only keep the value if I use a promise. (!?)
I am using a trigger.io (Forge) AJAX request, and upon success I update $rootScope.queries. Within the success block, $rootScope.queries is set correctly, as shown by the alert.
.run(function($rootScope, $state, $q) {
var retrieveHistory = function() {
forge.logging.log("Retrieving history");
// Retrieve the history
forge.request.ajax({
type: 'GET',
url: 'http://localhost:9000/json',
dataType: 'json',
success: function (data) {
$rootScope.queries = data["queries"];
alert("queries " + JSON.stringify($rootScope.queries));
},
error: function (error) {
}
});
}
retrieveHistory();
At this point though, after retrieveHistory() has been called, $rootScope.queries is now empty. The view doesn't update and inspecting using the Chrome console shows that it is empty.
Let's say I add a promise to the function, but don't really use the promise for anything.
.run(function($rootScope, $state, $q) {
var retrieveHistory = function() {
var deferred = $q.defer();
forge.logging.log("Retrieving history");
// Retrieve the history
forge.request.ajax({
type: 'GET',
url: 'http://localhost:9000/json',
dataType: 'json',
success: function (data) {
$rootScope.queries = data["queries"];
alert("queries " + JSON.stringify($rootScope.queries));
},
error: function (error) {
deferred.reject("error " + JSON.stringify(error));
}
});
return deferred.promise;
}
var promise = retrieveHistory();
promise.then();
With this promise, $rootScope.queries keeps its value. The view updates and Chrome inspector shows the value is set correctly.
Why is this? I simply don't understand this behavior. Why can't I preserve the value of $rootScope.queries in the original code? Why does the promise keep the value?
ok, 2 questions.
why are you using trigger.ajax over $http pr resource which are angular native services hence are fully aware of angulars diges cycle not the case of external libraries.
why are you using rootscope you really shouldn't do that unles you are broadcasrting an event inside a service i know no good reason to polute your rootscope.
How ever your problem is likely to be doe to forge.ajax being outside angular digest so you need to execute.
$rootScope.$apply()
to let rootscope know there are somechangins he needs to be aware of

Resources