2

My API sends data in the following form:

{
  "2015-09-05 00:00:00+000000": 0, 
  "2015-09-06 00:00:00+000000": 2, 
  "2015-09-07 00:00:00+000000": 1
}

What I would like to do is read the data with AJAX (?) and store them in two separate variables.

val a = ['a', '2015-09-05', '2015-09-06', '2015-09-07']
val b = ['b', 0, 2, 1]

I am new in JavaScript and AJAX but this is what I have done so far:

    function GetData() {

        // 1. Instantiate XHR - Start 
        var xhr; 
        if (window.XMLHttpRequest) 
            xhr = new XMLHttpRequest(); 
        else if (window.ActiveXObject) 
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        else 
            throw new Error("Ajax is not supported by your browser");

        // 3. Specify your action, location and Send to the server - End
        xhr.open('GET', 'http://localhost:5000/generate-aggregations');
        xhr.send(null);

    }


    var data = JSON.parse(GetData());

    var array_keys = new Array();
    array_keys.push('a');
    var array_values = new Array();
    array_values.push('b');

    for (var key in data) {
        array_keys.push(key);
        array_values.push(data[key]);
    }
user706838
  • 5,132
  • 14
  • 54
  • 78
  • Extremely related: http://stackoverflow.com/questions/10415133/hash-keys-values-as-array . Check out the second answer with more votes. However, I would reconsider splitting your variable up like this if you don't have to. – Kyle Pittman Oct 03 '15 at 14:29
  • Can you please have a look on the updated sample code? I am using xhr (no idea what xhr is!) but looks like to work. Would you recommend xhr? Also, how can I split the JSON response into two list? – user706838 Oct 03 '15 at 14:33
  • What are you trying to accomplish with these 2 lists? – Kyle Pittman Oct 03 '15 at 14:37
  • ultimately, I am trying to create a d3 plot. – user706838 Oct 03 '15 at 14:39

0 Answers0