user5773634
user5773634

Reputation:

Why this json_encode returns string instead of object?

I'm using json_encode to convert an associative array to JSON format. But When I try to print the property of data accessed through Ajax from this PHP file, it shows undefined. When I checked the type of data, it returns string.

$elem1= "<div class='menuitems'>
                        <div class='menu1'>".$row['name']."<span class='srno'>".$row['srno']."</span></div>
                        <div class='menu2'>".$row['email']."</div>
                        <div class='menu3'>".$row['password']."<span class='cross'>X</span></div>
                        <div class='clear'></div>
                    </div>";
$elem2=$row['category'];
$array=array(
        "elem1"=>"$elem1",
        "elem2"=>"$elem2"
    );
echo json_encode($array);

Why is it so? How can I access the elem1 and elem2 through this string?

Upvotes: 4

Views: 6876

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167212

Always HTTP responses will be of string data type. You need to parse the JSON before you can use. There are two ways. You need to use:

$.getJSON(url, function (data) {
    typeof data; // object
});

In contrast to:

$.get(url, function (data) {
    typeof data; // string
});

If you are using the above one, you need to use:

$.get(url, function (data) {
    typeof data; // string
    data = JSON.parse(data);
    typeof data; // object
});

Note: I am using AJAX from jQuery. The conversion, which is very specific is in pure JavaScript.

Upvotes: 2

Related Questions