1

I've done something like so

PHP

 $returndata[$num] = array(
                        'type' => $num,
                        'id'=>$desc['id'],
                        'title' => $desc['title'],
                    );
    json_encode($returndata);

AJAX

success: function(data){
       var arr = data;
       for (i in arr)
            {
              console.log(arr[i].title);
            }
     }

ALSO Tried

success: function(data){
            $.each(data, function(i, val){
                console.log(val.title);
            });  
         }

I have the following JSON that i would like to put in separate var to use in HTML.

{
 "5" :
      {
         "type":"5",
          "id":"590",
          "title":"Little Lamb"
      }
 "7" : 
      {
         "type" : "7",
         "id":"540",
         "title":"Little Lamb 2"
      }
}

But I can't get the titles.

2
  • 1
    set dataType:'json' in your ajax call, I think you are missing that Commented Feb 2, 2014 at 4:37
  • @PranavCBalan thanks for the heads up, i didn't know this is so important. Commented Feb 2, 2014 at 4:38

1 Answer 1

1

Try this:

for(key in data){
    if(data.hasOwnProperty(key)){
        console.log(data[key].title);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this worked after adding the dataType: 'json' as suggested by @Pranav C Balan in the comments.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.