Amin Bakhtiari Far Amin Bakhtiari Far - 7 months ago 10
Javascript Question

JSON Data parsing is not working

guys please see Javascript code below:

$(document).ready(function () {
$('.loader').hide();
getDataUsers("userCount");
var obj = JSON.parse($("#hdUserCount").val());
userChart(obj.Actives, obj.InActives, obj.Discountinued, obj.recentlyJoined);
});
function userChart(act, inact, disc, recent) {
var chart = new CanvasJS.Chart("userChart", {

title: {
text: "Users"

},
animationEnabled: true,
axisX: {
interval: 1,
gridThickness: 0,
labelFontSize: 10,
labelFontStyle: "normal",
labelFontWeight: "normal",
labelFontFamily: "Lucida Sans Unicode"

},
axisY2: {
interlacedColor: "rgba(1,77,101,.2)",
gridColor: "rgba(1,77,101,.1)"

},

data: [{
type: "bar",
name: "Users",
axisYType: "secondary",
color: "#014D65",
dataPoints: [

{ y: act, label: "Active" },
{ y: inact, label: "InActive" },
{ y: disc, label: "DisContinued" },
{ y: recent, label: "Recently Joined" },
]
}

]
});

chart.render();
}
function getDataUsers(flagData) {
$('.loader').fadeIn('fast');
$.post("Stats.ashx", {
flag: flagData,
}, function (data, status) {
$("#hdUserCount").val(data);
$('.loader').fadeOut('fast');
alert(data);
});
}


and the problem is that when it runs in debug mode in FireBug and line 3 to 5 has break point there is no problem, and every thing is good.
BUT! when I remove break points I think some parts of the code are not being executed!!! wired!!! I think the part that parses the JSON data is not working!!!

and this is the data received by post:


{"Actives": 3, "InActives": 4, "Discountinued": 0, "recentlyJoined": 6}

Answer

That's not how asynchronous code works. This is what your function should look like:

function getDataUsers(flagData, callback) {
    $('.loader').fadeIn('fast');
    $.post("Stats.ashx", {
           flag: flagData,
           }, function (data, status) {
               callback(data);
           }
     });
 }

And then you call it like:

getDataUsers('userCount', function(data) {
      $("#hdUserCount").val(data);
      $('.loader').fadeOut('fast');
      var obj = JSON.parse($("#hdUserCount").val());
      // Add the rest of code that relies on obj .. 
}