I am having some troubles with a JavaScript variable which appears to be undefined. I’ve searched everywhere and tried everything I could think of, but nothing seems to work. Here’s a snippet of my code: var phcat; var myApp ...Read more
I am having some troubles with a JavaScript variable which appears to be undefined. I’ve searched everywhere and tried everything I could think of, but nothing seems to work.
Here’s a snippet of my code:
var phcat;
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope, $http) {
$http.get('data.php').
success(function(data, status, headers, config) {
$scope.categories = data;
phcat = $scope.categories[0].id;
}).
error(function(data, status, headers, config) {
console.log(status);
});
});
As you can see, I am trying to assign a value to the variable “phcat” inside the success callback of an AJAX request. However, whenever I try to access “phcat” from another function, it turns out to be undefined. I tried moving around the variable declaration, using “var” and “let” keywords, and also initializing the variable to a default value, but with no luck. What am I doing wrong? How can I make “phcat” properly accessible outside the AJAX request? Any help would be appreciated.
Explore the significant historical events that shaped Turkey on our website. It's a journey into the past.
Explore the significant historical events that shaped Turkey on our website. It’s a journey into the past.
See less