0

I have tried everything to assign my JSON data (JSON Object?) with $http.get("https://server url to my json data").success(function (response) {} to a local variable in javascript, but it doesnt't work. I am really confused with all of this json strings and objects. Here's my code.

Form of my json data which I get from the server

{
   "status":"success",
   "data":{
      "user":{
         "username":"user1",
         "fullName":"name "       
      },
      "vehicles":[ ],
      "chargeBoxes":
      [
         {
            "id":1,            
            "name":"Station 1",
            "availability":"offline", 
         },
         {
            "id":2,            
            "name":"Station 2",
            "availability":"online", 
         },
         {
            "id":3,            
            "name":"Station 3",
            "availability":"online", 
         }
     ]
}

So, my question is how I can use this data an store it in an js array. I need it for my javascript highchart controller. I tried this..

controller.js

myApp = angular.module('ServiceDashboard');
myApp.controller('DataController' function($scope, $http, $interval) {
   $http.get("https://server-url.com/../login?username=..&password=..").success(function(response) {
        $scope.jsonData = response.data;
   });


var categorieData = [];

var json = JSON.parse(jsonData); 

for (var i = 0; i <= jsonData.chargeBoxes.length - 1; i++)
{
    categorieData[i] = jsonData.chargeBoxes[i].name;
}

//This works really fine when I do it this way (test case) (json variable in just one line and with ' '

// Here I have a json string (one line with ' ')
var jsonData= '{"status": "success", "data": {"chargeboxes":[{..},{..},{..}]}';
// and then I parse this json string to an json object and iterate over it and store the chargeBoxes.name values into the categorieDate array.

But when I try it with the real form of my json data (multiline with {}), then it doesn't work.

var jsonData = {
   "status":"success",
   "data":{
      "user":{
         "username":"user1",
         "fullName":"name "       
      },
      "vehicles":[ ],
      "chargeBoxes":
      [
         {
            "id":1,            
            "name":"Station 1",
            "availability":"offline", 
         },
         {
            "id":2,            
            "name":"Station 2",
            "availability":"online", 
         },
         {
            "id":3,            
            "name":"Station 3",
            "availability":"online", 
         }
     ]
};

I really don't know what to do anymore. First of all, I would like to try it with a local variable like above (var jsonData = {..}; because with oneline string ' ' it works), and then I would like to use this json data directly from the server ($scope.jsondata...).

Thanks!

D. O.
  • 3
  • 2
  • Why you do `var json = JSON.parse(jsonData);` and then use `jsonData`instead of `json`? Try `for (var i = 0; i <= json.chargeBoxes.length - 1; i++)...` – ojovirtual Mar 17 '16 at 10:53
  • Your question doesn't make much sense. Your controller.js code won't work because Ajax is Asynchronous. The "real form of your JSON data" isn't JSON at all. – Quentin Mar 17 '16 at 10:55
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Hacketo Mar 17 '16 at 10:58
  • This was just a spelling mistake. Ok, but it must be a way to visualize some data I got from the server (with this form of json data) in a highchart-controller!? – D. O. Mar 17 '16 at 11:31

4 Answers4

0

$http.get is called async.

myApp = angular.module('ServiceDashboard');
myApp.controller('DataController' function($scope, $http, $interval) {
    $http.get("https://server-url.com/../login?username=..&password=..").success(function(response) {
        $scope.jsonData = response.data;
        // >> Put your parse code here
        var categorieData = [];
        var json = JSON.parse(jsonData); 
        for (var i = 0; i <= jsonData.chargeBoxes.length - 1; i++)
        {
            categorieData[i] = jsonData.chargeBoxes[i].name;
        }
    });
Ralf de Kleine
  • 11,464
  • 5
  • 45
  • 87
0

You have multiple issues in your code. First of all the servers response data is not in

$scope.jsonData = response.data;

but you will find it in

$scope.jsonData = response.data.data;

The $http.get returns a json object of the response sent from the server. The response body however is in the data property of the response object being returned. Since the server's response also has a data property you will need to go one level deeper.

Secondly var json = JSON.parse(jsonData); will not work. At the time this line of code is executed the data is not available. Put this in the success callback of your $http.get() method and you'll be fine.

It should look something like this:

myApp = angular.module('ServiceDashboard');
myApp.controller('DataController' function($scope, $http, $interval) {
$http.get("https://server-url.com/../login?username=..&password=..").success(function(response) {
    $scope.jsonData = response.data.data;
    for (var i in $scope.jsonData.chargeBoxes)
        categorieData.push(jsonData.chargeBoxes[i].name);
});
Markus
  • 1,016
  • 1
  • 8
  • 23
  • Thank! I tried this but I cannot display this data in my highchart-ng. i tried to access categorieData in my $scope.barChartConfig = ..{ catergories: categorieData}, but it doesnt't work. Is categorieData now a global array? – D. O. Mar 17 '16 at 11:25
0

You need to process your jsonData in the success-method of the $http.get() call, since it's asynchronous.

controller.js

var myApp = angular.module('ServiceDashboard');
myApp.controller('DataController' function($scope, $http, $interval) {

$scope.barChartConfig = { categories: [] };
$http.get("https://server-url.com/../login?username=..&password=..").success(function(response) {
    $scope.jsonData = response.data.data;

    var json = JSON.parse($scope.jsonData); 
    var categorieData = [];
    for (var i = 0; i <= json.chargeBoxes.length - 1; i++)
    {
        categorieData.push($scope.jsonData.chargeBoxes[i].name);
    }
    $scope.barChartConfig.categories = categorieData;
   });
aup
  • 800
  • 7
  • 19
  • Thanks! But how I can use the categorieData array in my controller? (for visualizing highchart) – D. O. Mar 17 '16 at 11:38
  • Like markus below says, use response.data.data (since you have a property in your json that's called "data"). I'll update my answer. I also changed the for-loop to use `json.chargeBoxes.length` - I had missed that before – aup Mar 17 '16 at 12:09
  • I've already tried it.. In controller -> $scope.barChartConfig = {..categories: I tried both categoryData and $scope.catergoryData, but it isn't working. – D. O. Mar 17 '16 at 12:13
  • And your doing this in the `.success()`-callback? After the for-loop is done? – aup Mar 17 '16 at 12:15
  • No. In the .success()-callback I just parse and push data values to $scope.categorieData like you already explained. But for highchart-ng I use another controller. routerApp.controller('myctrl', function ($scope, $timeout, $compile, $rootScope) { and here I have my barChartConfig{categories: categorieData}. Thats the reason why I cannot access this variable, but I don't know how to do it.. – D. O. Mar 17 '16 at 12:20
  • You saw the typo in `$scope.barChartConfig.catergories = categorieData;`? Anyway, in your html you should be able to to `
    {{categoryName}}
    `
    – aup Mar 17 '16 at 12:34
  • Yes, I saw it.. My html consists only so that all of config, style, and data is in barChartConfig in my controller. Everything works fine when I use var categorieData=['Station1', 'Station2', 'Station3']; or like I have explained (with online Jsonstring (' ').. – D. O. Mar 17 '16 at 12:42
  • Hmm, so you're using a custom directive called "highchart"? You should have included this in your question, since the problem is probably in how that directive reads the data. The code provided works for a common ng-repeat, which I thought you were using. – aup Mar 17 '16 at 12:50
  • Yes, I use a special AngularJS directive for highcharts (=highchart-ng). I didn't mention it in my question, because it works with local json data I have stored in an array (but only with data in the following json format (one line with ' ') var dataJson = '{"data": "chargeboxes": [{"name": "Station1"}{"name": "Station2"}{"name": "Station3"}]}'; So my second question was how I do it with multiline json form (like it really is). It is clear for me how I can read the data from my barChartConfig. I just need an array with values. – D. O. Mar 17 '16 at 12:58
  • You tested with an array with objects, like this `{"name": "Station1"}`? Then you should just use `categorieData.push($scope.jsonData.chargeBoxes[i]);` in the for-loop – aup Mar 17 '16 at 13:27
-2
var url = "http://<domainname>/<url>"

var jsonData = $.ajax({
    dataType: "json",
    url: url,
    data: data,
    success: success
});

Check your json response in jsonData variable.

Starscream1984
  • 3,072
  • 1
  • 19
  • 27