2

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?

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

3 Comments

@Beardy Is the output really like shown above or is it "[{"response":0}]"?
As I put it from being copied and pasted from Console.log
@Beardy Extended my answer.
1

1)

console.log(data[0].response)

2)

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.