4

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?

4
  • JSON is a string format ... Commented Jul 19, 2016 at 10:03
  • Call json_decode() to decode it. Commented Jul 19, 2016 at 10:03
  • 1
    The whole point of JSON is to convert arrays and objects into strings, so you can send them over the network or save it in a file. Commented Jul 19, 2016 at 10:04
  • Post your AJAX code Commented Jul 19, 2016 at 10:04

1 Answer 1

2

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.

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

13 Comments

You used $.get. Is it valid for $.ajax as well? What's the difference between $.get and $.ajax?
@VikasKumar Yes! $.get is a short cut for $.ajax using URL.
Ok you don't need to define type etc ?
@VikasKumar No! That's the whole point of using a shortcut. :)
@VikasKumar Ah don't worry. Will get soon. There's always a next chance... :) Keep trying.
|

Your Answer

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