samurdhilbk
samurdhilbk

Reputation: 429

Array exists and is populated but cannot access individual elements on AJAX response

I'm executing an AJAX call in my website running on WordPress 4.7.2. I'm returning an array back from the PHP function which handles the request, with wp_json_encode(). When I print the data array in the AJAX success function it's exactly as expected. But it gives me undefined when I try to print the individual element inside the array.

The PHP handler function is like this

function ajaxHandler(){
     //do something
     $ret = array( 'score'=>$score );
     echo wp_json_encode( $ret );
     wp_die();
}

And in my AJAX,

$.ajax({
    type: 'POST',
    url: ajaxurl,
    data: {'action': $my_Action},
    success: function(data) {
        console.log(data);
        console.log(data["score"]);
        //also tried console.log(data.score) with same result
    },
    error: function(data){
        console.log("not successful");
    }
});

The console log in Chrome

enter image description here

Upvotes: 1

Views: 51

Answers (1)

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

Parse the response data into javascript object inside success callback :

success: function(data) {
    var data = JSON.parse( data );
    console.log(data);
    console.log(data["score"]);
    //also tried console.log(data.score) with same result
}

Another way is, put dataType : 'json' inside ajax properties :

$.ajax({
  .....
  .....
  dataType : 'json',
  ......
});

Upvotes: 1

Related Questions