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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With