3

I have a php program where I just test some sample data. I am getting error as missing ] after element list. How can I read this?

$dataDetailsList = array();
array_push($dataDetailsList, array('a' =>'1','b' =>'2','c' =>'3','d' =>'4','e' =>'5'));
echo json_encode(array("DataDetailsList"=>$dataDetailsList));

Then in my jQuery processor I am doing like this.

function requestData() {
    $.ajax({
        url: 'live-server-data.php',
        success: function(data) {
            //alert(json);
            var jsonData = eval(" (" + data + ") ");
        },
        cache: false
    });
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
user837306
  • 857
  • 3
  • 18
  • 32

3 Answers3

4
function requestData() {
    $.ajax({
        url: 'live-server-data.php',
        success: function(data) {
            //alert(json);
            var jsonData = data;

        },
        cache: false,
        dataType: 'json' //data type that it will return 
    });
}
Naftali
  • 144,921
  • 39
  • 244
  • 303
3

Don't use eval is evil. Instead of this use:

JSON.parse(data); // not supported in IE7 and below

I think you need to try

dataType: 'json'

That is,

$.ajax({
    url: 'live-server-data.php',
    dataType: 'json',
    success: function(data) {
        var jsonData = data;
        console.log(jsonData);
        $.each(jsonData.DataDetailsList, function(key, val) {
             var key = Object.keys(val)[0],
                 value = val[key];
             console.log(key); // output: a, b, c ...
             console.log(value); // output: 1, 2, 3,...
            // alternative
            for(var key in val) {
                console.log(key);
                console.log(val[key]);
            }
        });
    },
    cache: false
})
Community
  • 1
  • 1
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
2

You should just set the dataType to json and jQuery will do the trick for you..

$.ajax({
    url: 'live-server-data.php',
    dataType: 'json',  //Added dataType json
    success: function(data) {
        //Now data is a javascript object (JSON)
    },
    cache: false
});
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134