Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a php page from which I get response in json:

[{'com':'something'},{'com':'some other thing'}]

I want to loop it and append each to a div.

This is what I tried:

var obj = jQuery.parseJSON(response);
$.each(obj.com, function(key,value) {
  alert(key+':'+value);
}

This alerts as undefined, and also response is the json array..

Please help.

share|improve this question
    
try alert(this); –  KoIIIeY Dec 25 '13 at 11:46
    
@KoIIIeY doesn't show any alert.. –  blo Dec 25 '13 at 11:49

4 Answers 4

up vote 3 down vote accepted

Your array has default keys(0,1) which store object {'com':'some thing'} use:

var obj = jQuery.parseJSON(response);
$.each(obj, function(key,value) {
  alert(value.com);
}); 
share|improve this answer
    
Thanks alot for explaining and helping out , it works and helping out :D –  blo Dec 25 '13 at 11:59
    
Your welcome!!! –  Dell Dilshod Dec 25 '13 at 12:29
    
Anyway I can fade each? I used .hide().fadeIn(800); while appending, but it fades the whole thing at once, is it possible to fade 1 by 1? –  blo Dec 25 '13 at 13:22
    
You have to rebind event($(...).bind("") Or attachEvent()) after(before provide control to user) adding any element. –  Dell Dilshod Dec 26 '13 at 7:28
1  
@ChristoKiwi: Thanks! –  Dell Dilshod Jan 6 at 15:35

Try this:

var data = jQuery.parseJSON(response);
$.each(data, function(key, item) 
{
   console.log(item.com);
});

or

var data = $.parseJSON(response);

$(data).each(function(i,val)
 {
    $.each(val,function(key,val)
  {
          console.log(key + " : " + val);     
  });
});
share|improve this answer
    
Loops but shows [object, object] also I'm getting the json via ajax call –  blo Dec 25 '13 at 11:52

You are iterating through an undefined value, ie, com property of the Array's object, you should iterate through the array itself:

$.each(obj, function(key,value) {
   // here `value` refers to the objects 
});

Also note that jQuery intelligently tries to parse the sent JSON, probably you don't need to parse the response. If you are using $.ajax(), you can set the dataType to json which tells jQuery parse the JSON for you.

If it still doesn't work, check the browser's console for troubleshooting.

share|improve this answer
    
Nothing happens, not showing alert.. –  blo Dec 25 '13 at 11:50
var data=[{'com':'something'},{'com':'some other thing'}];
$.each(data, function() {
  $.each(this, function(key, val){
    alert(val);//here data 
      alert (key); //here key

  });
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.