Brendan Goodenough
Brendan Goodenough

Reputation: 117

JSON Returning Undefined

I've been trying to read JSON through jQuery/AJAX but so far it keeps returning undefined.

$.ajax({
    type: "POST",
    url: "php/ajax/retrieve.php",
    dataType: "json",
    success: function(data) {
      console.log(data);
      $("#items").html(data);

      $.each(data, function(key, val) {
        console.log(key + ' ' + val);
        $("#items").append('\
          <div class="item-section" id="' + key + '">\
          <div class="item">\
            <h3>' + val.current_status + '</h3>\
          </div>\
          </div>\
        ');
      });
    }
  });

Inside the console the output for the log inside the iteration is as follows, but when I try to add val.current_status in the HTML it just says "undefined":

0 {"id":"4","creation_date":"15 Jan 2015 - 07:32 AM","current_status":"Pending", [... and so on]

Any help is appreciated.

Upvotes: 0

Views: 5234

Answers (2)

JDB
JDB

Reputation: 25820

If your console is outputting "{"id":"4","creation_date":"15 Jan 2015 - 07:32 AM","current_status":"Pending"..." then your "object" is a string, not a JSON object. Check out the example below. You should be seeing "[object Object]" in your console window.

My guess is that your server is accidentally converting the JSON to a string value at some point, complete with escaped quotation marks, etc. Perhaps you've called the JSON serializer twice, somehow?

This is why you shouldn't attempt to convert data to a string in your console. You're thinking of it like it's a C console, where everything has to be a string to understand it. Browser consoles are much smarter and more more interactive than that... you should output the actual value so that you can see its type and work with the properties, etc:

console.log( key, val );

  var key = 0,
      val_str = "{\"id\":\"4\",\"creation_date\":\"15 Jan 2015 - 07:32 AM\",\"current_status\":\"Pending\"}",
      val_obj = {"id":"4","creation_date":"15 Jan 2015 - 07:32 AM","current_status":"Pending"};

  $( '#str' ).text( key + ' ' + val_str );

  $( '#obj' ).text( key + ' ' + val_obj );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="str"></div>
<div id="obj"></div>

Upvotes: 1

Rafael
Rafael

Reputation: 7746

Iterate Array of Objects

$.each(data, function(i, val) {

    $.each(val, function(k, v) {
        // do something 
    });

});     

Upvotes: 0

Related Questions