I have the following javascript:
$.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
moulding_1_cost = data.moulding.cost;
moulding_1_width = data.moulding.width;
});
cost_of_moulding = ( ( 2 * ( width + ( 2 * moulding_1_width ) ) + 2 * ( height + ( 2 * moulding_1_width ) ) ) / 1000 ) * moulding_1_cost;
$('#item_total').html( cost_of_moulding );
The problem is that the two variables moulding_1_cost and moulding_1_width are undefined outside of the getJSON call. How do I make these two variables available outside the getJSON call?
The variables aren’t set until that callback runs (when the server comes back with the JSON data), so you need to call whatever code uses them from that callback, like this:
Or call another function like this:
In either case what remains true is you need to trigger whatever uses the data once you have the data, all asynchronous operations are like this.