2

I have a php file in which I'm getting data from server. The output of that php file is a variable containing the data in json format.

PHP File:

<?php 
$dbHostName = "localhost";
$dbUserName = "venseld";
$dbUserPass = "wecuuu";
$dbName = "veseldb";
try
{
    global $dbHostName, $dbUserName, $dbUserPass, $dbName;
    $pdo = new PDO("mysql:host=$dbHostName;dbname=$dbName", $dbUserName, $dbUserPass);  
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  

    $statement = $pdo->prepare("SELECT round(AVG(AssetUnderMgmt)) as aum FROM tblDetails GROUP BY City");
    $statement->execute();
    $results=$statement->fetchAll(PDO::FETCH_ASSOC);
    $json=json_encode($results);

    echo $json; <-- this is what I want to get, I'm getting it.

}
catch(PDOException $e) 
{
    echo "Error: " . $e->getMessage();
}
$pdo = null;
?>

Now I want to store the result in a javascript variable, for which I've done the following code.

<script type="text/javascript">
var jsonObj;
$.post( "assetsData.php", function(data) {  
    jsonObj = data;  <-- Here the data is coming fine.
}); 

The data printed by above alert is

 [{"aum":"252"},{"aum":"250"},{"aum":"251"},{"aum":"248"},{"aum":"255"},{"aum":"250"},{"aum":"252"},{"aum":"250"},{"aum":"250"},{"aum":"250"},{"aum":"254"},{"aum":"252"},{"aum":"251"},{"aum":"246"},{"aum":"250"},{"aum":"255"},{"aum":"247"},{"aum":"253"},{"aum":"254"},{"aum":"257"},{"aum":"246"},{"aum":"250"},{"aum":"254"},{"aum":"249"},{"aum":"251"},{"aum":"248"},{"aum":"249"},{"aum":"253"},{"aum":"249"},{"aum":"251"},{"aum":"250"},{"aum":"249"},{"aum":"253"},{"aum":"253"}]


//First try
alert(jsonObj) <-- this gives undefined error.

// Second try
object = JSON.parse(jsonObj); 
var my_array = new Array(); 
for(var key in object ){ 
    my_array[key] = object[key]; 
}
alert(my_array); <--Gives: Uncaught SyntaxError: Unexpected token u

// third try
alert(jsonObj[0].aum); <-- Cannot read property '0' of undefined

// fourth try
alert(jsonObj['aum']); <-- Cannot read property 'aum' of undefined

 </script>

This is the place where I want to access those (json)values according to it's index.

FusionCharts.ready(function () {
    var salesByState = new FusionCharts({
        "type": "maps/maharashtra",
        "renderAt": "chartContainer",
        "width": "100%",
        "height": "700",
        "dataFormat": "json",
        "dataSource": {
            "chart": {
                "theme": "fint",
                    "caption": "Annual Assets (demo)",
                    "entityFillHoverColor": "#cccccc",
                    "numberPrefix": "Rs.",
                    "showLabels": "1",
                    "legendPosition": "BOTTOM"
            },
        //Defining color range for data range
        "colorrange": {
            "minvalue": "0",
                "startlabel": "Low",
                "endlabel": "High",
                "code": "e44a00",
                "gradient": "1",
                "color": [{
                "maxvalue": "30000",
                    "displayvalue": "Average",
                    "code": "f8bd19"
            }, {
                "maxvalue": "100000",
                    "code": "6baa01"
            }]
        },
       "data": [{
            "id": "IN.MH.AH",
                "value": obj[0].aum  <-- These are the places where I want to access the values inside the 'jsonObj'. Is this correct, if not then which is correct way?
        }, {
            "id": "IN.MH.AU",
                "value": obj[3].aum
        }, {
            "id": "IN.MH.YA",
                "value": "33038"
        }]
    }
});
salesByState.render();
});
overlord
  • 1,059
  • 1
  • 14
  • 21

1 Answers1

0

Try this code:

var jsonObj;
$.post( "assetsData.php", function(data) {  
    jsonObj = data;
});

If your json likes this:

[{"aum":"249"},{"aum":"253"},{"aum":"253"}]

You can access your values like this:

jsonObj[0].aum

However, be sure that your php code generate the json response like this:

<?php 
    echo json_encode(array(myObj1, myObj2, myObj3));
?>

Here is an example taken from jQuery.post() documentation:

Example: Post to the test.php page and get content which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>).

    $.post( "test.php", { func: "getNameAndTime" }, function( data ) {
         console.log( data.name ); // John
         console.log( data.time ); // 2pm
    }, "json");

EDIT: Proposition from Ankit:

var jsonObj;
$.ajax({
    type: 'POST',
    url: "assetsData.php",
    data: '',
    dataType: 'json',
    async: false,
    success: function(data) {
        jsonObj = data;
    }
});
alert(jsonObj[0].aum);
Community
  • 1
  • 1
Stephan
  • 41,764
  • 65
  • 238
  • 329
  • @overlord Please check the update in my answer. – Stephan Feb 12 '15 at 11:07
  • I'm doing similar thing, but getting "Cannot read property '0' of undefined". – overlord Feb 12 '15 at 11:12
  • @overlord Can you post your php code in your post? – Stephan Feb 12 '15 at 11:15
  • @overlord On this line, `jsonObj = data; <-- Here the data is coming fine.` what does `alert(data)` produce? – Stephan Feb 12 '15 at 11:31
  • @Stephan: please check now, I've updated the code. – overlord Feb 12 '15 at 11:36
  • @Ankit: Your answer produces this error: Cannot use 'in' operator to search for '488' in [{"aum":"252"},{"aum":"250"},{"aum":"251"},{"aum":"248"},{"aum":"255"},{"aum":"250"},{"aum":"252"},{"aum":"250"},{"aum":"250"},{"aum":"250"},{"aum":"254"},{"aum":"252"},{"aum":"251"},{"aum":"246"},{"aum":"250"},{"aum":"255"},{"aum":"247"},{"aum":"253"},{"aum":"254"},{"aum":"257"},{"aum":"246"},{"aum":"250"},{"aum":"254"},{"aum":"249"},{"aum":"251"},{"aum":"248"},{"aum":"249"},{"aum":"253"},{"aum":"249"},{"aum":"251"},{"aum":"250"},{"aum":"249"},{"aum":"253"},{"aum":"253"}] in jquery.min.js:2 – overlord Feb 12 '15 at 11:39
  • 1
    @overlord: Use $.ajax instead of $.post and use async : false, it will allow you to use variable out of scope. var jsonObj; $.ajax({ type: 'POST', url: "assetsData.php", data: '', dataType : 'json', async:false, success: function(data) { jsonObj = data; } }); alert(jsonObj[0].aum); – Ankit Feb 12 '15 at 13:29