xrcwrn
xrcwrn

Reputation: 5337

How to parse php response as json in jQuery

In php:

header('content-type: application/json; charset=utf-8');
$res = array("success" => true, "status" =>array(),"path" =>array());
echo(json_encode($res));

I want to access path from above array.

In jQuery I am trying

on("success", function (Text) {
                console.log("l path " + Text[0].path);
            $.each(Text[0].path, function(i,k){
                       console.log(i+"  "+k);
});

It is throwing an error:

Uncaught TypeError: Cannot read property 'path' of undefined'

Upvotes: 2

Views: 58

Answers (2)

Reserge
Reserge

Reputation: 65

I'd use

on("success", function (Text) {
var response = JSON.parse(Text);
console.log("l path " + response[0].path);
$.each(response[0].path, function(i,k){
    console.log(i+"  "+k);
});
}

Upvotes: 0

Manwal
Manwal

Reputation: 23846

Use JSON.parse(), like following:

on("success", function (Text) {
    var response = JSON.parse(Text);
    console.log("l path " + response.path);
    $.each(response.path, function(i,k){
        console.log(i+"  "+k);
    });
}

Upvotes: 3

Related Questions