javascriptjqueryajax

AJAX JSON returns undefined


I have simple ajax query

$.ajax(
{
    url:'ADMPANEL_POST.php',
    type:'POST',
    data:{'z':'1'},
    dataType:'json',
    success:function (result) {
        alert( "Data recieved: " + result.x );
        $('#result').append(result.x);
    }
});

in ADMPANEL_POST.php I try to get z=1 and have appropriate handler, and I expect to return data_str using json_encode to ajax success function

if(isset($_POST['z'])) 
{
    $init_x = 'test';
    $data_str[] = array('x' => $init_x);
    if($_POST['z']=='1') {
        echo json_encode($data_str, true);
    }
}

However I receive undefined value of data.x in alert message. Can't figure out what is the problem.

P.S.: saw this, but it didn't help JSON returning as undefined


Solution

  • Your format is wrong, if you want result.x == 'test' use $data_str = array('x' => $init_x);.