Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

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).

share|improve this answer
 
it come up undefined –  Donald Sep 18 at 14:16
 
@Beardy Is the output really like shown above or is it "[{"response":0}]"? –  Sirko Sep 18 at 14:18
 
As I put it from being copied and pasted from Console.log –  Donald Sep 18 at 14:20
 
@Beardy Extended my answer. –  Sirko Sep 18 at 14:22
add comment

1)

console.log(data[0].response)

2)

for(var i in data){
  console.log(data[i].response);
}
share|improve this answer
add comment
success:function(data){
    data = $.parseJSON(data);
    console.log(data[0].response);
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.