1

when the page loads I want to get a json as so:

$.getJSON(_routes['salesInAMonthJS'], { month: "September 2016" }).then(
    function(d){
        console.log(d);
    }
);

this

$.getJSON(_routes['salesInAMonthJS'], { month: "September 2016" });

gives me back

{"9":{"name":"alex lloyd","country":"Germany","antiquity":"new client","amount":"0.0 USD"},"10":{"name"
:"asdasdsadasda dasda","country":"Afghanistan","antiquity":"new client","amount":"0.0 USD"},"11":{"name"
:"Alex Lloyd","country":"American Samoa","antiquity":"new client","amount":"0.0 USD"},"12":{"name":"alex
 lloyd","country":"Aruba","antiquity":"new client","amount":"0.0 USD"},"5":{"name":"surgeon bueno","country"
:"Spain","antiquity":"renewal","amount":"2686.97 USD"}}

However when a user clicks a button I want to display the data stored in d

for example:

$(document).on("click ", ".tick", function(e) {
    e.preventDefault();
    $.each(d, function(i, item) {
        &("div.container").append(d[i].name);
    });
});

However this doesn't seem to work, any idea what I'm doing wrong? Thanks

jrbedard
  • 3,662
  • 5
  • 30
  • 34
user1937021
  • 10,151
  • 22
  • 81
  • 143
  • `&("div.container")` is a typo for `$("div.container")`. – Barmar Sep 21 '16 at 18:48
  • 1
    You have a variable scope problem. `d` is local to the `$.getJSON` callback function, you can't access it in another function. – Barmar Sep 21 '16 at 18:50

2 Answers2

0

Something like this?

$.getJSON(geocodingAPI, function(json) {
  $.json = json;
});

$('button').on('click', function() {
  alert($.json.status)
});

http://jsfiddle.net/eywpvyrr/1/

Sam Battat
  • 5,725
  • 1
  • 20
  • 29
0

The scope of d is just the callback function. You can move the click binding into that so you can access it.

$.getJSON(_routes['salesInAMonthJS'], { month: "September 2016" }).then(function(d){
    $(document).on("click ", ".tick", function(e) {
        e.preventDefault();
        $.each(d, function(i, item) {
            $("div.container").append(d[i].name);
        });
    });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612