Im trying to retrieve json response and below code snippet shows the way I've implemented it.The problem I'm having there is at the first attempt I can't fetch data through an alert. Actually it gives me an empty result. But once I added another alert right after the previous alert it gives me the out-come from the second alert. I can't figure out the reason for this.
My code :
var sales = [];
$.ajax({
url: 'getSalesAction',
dataType: 'json',
cache: false,
success: function (data) {
$.each(data, function (key, value) {
var weekDaySale = {day: value.day,
amount: value.amount
};
sales.push(weekDaySale);
});
},
error: function () {
alert('error');
}
});
alert(sales);//first alert (returns empty alert)
alert(sales); //second alert.( returns [object Object],[object Object],[object Object]])
What is the reason for not giving the out-put from the first alert ?. Thank you.