ngplayground
ngplayground

Reputation: 21617

PHP jQuery json_encode

PHP

$results[] = array(
    'response' => $response
);
echo json_encode($results);

Using the above returns to my jQuery the following data

Part of .ajax()

success:function(data){
    console.log(data);
}

Outputs

 [{"response":0}]

How could I change console.log(data) to pick the value of response?

Upvotes: 2

Views: 38015

Answers (3)

Sirko
Sirko

Reputation: 74036

If you set datatype: "json" in the .ajax() call, the data object you get, contains the already parsed JSON. So you can access it like any other JavaScript object.

console.log( data[0].response );

Otherwise you might have to parse it first. ( This can happen, when the returned MIME type is wrong.)

data = JSON.parse( data );
console.log( data[0].response );

Citing the respective part of the jQuery documentation:

dataType

If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

Upvotes: 10

ngplayground
ngplayground

Reputation: 21617

success:function(data){
    data = $.parseJSON(data);
    console.log(data[0].response);
}

Upvotes: 0

Falci
Falci

Reputation: 1873

1)

console.log(data[0].response)

2)

for(var i in data){
  console.log(data[i].response);
}

Upvotes: 1

Related Questions