3

I know there are 1 million and 1 questions on this, but I cannot seem to find an answer.

I am receiving data via PHP as such

echo json_encode($result); 

From a typical MYSQL query.

I get the result back like this in the console.

[{"id" : "1", "name" : "bob"}] 

I am trying to use $.each to iterate through this so I can process my results but I only get errors, undefineds or 0[object Object].. things like that.

My goal is to append each value to a input box (retrieving data from a table to put into an edit box).

$.post('getstuff.php', { id : id } function(data){
  $.each(data), function(k,v){
    $('input[name= k ]').val(v);
  });
});

As you can see i was hoping it was as simple as a key=>value pair but apparantly not. I have tried parsing, stringifiying.. really I am lost at this point. I also cannot tell $.post that I am using JSON because I am using a more arbitrary function, but am just posting that as my example.


Edit

            var retrievedData = JSON.parse(data);
        $.each(retrievedData, function(k,v){
            for (var property in retrievedData) {
                if (retrievedData.hasOwnProperty(property)) {
                    console.log(k);
                    console.log(v);
                    console.log(property);
                    //$('input[name= k ]').val(v);
                }
            }
        });
user3697407
  • 101
  • 7

4 Answers4

2

In your second code sample, retrievedData is an array, which you iterate using jQuery $each...

$.each(retrievedData, function(k, v) {

OK so far. But then you try to iterate retrievedData again like an object, which it isn't. This is why you are getting undefined messages in the console

for (var property in retrievedData) {
    if (retrievedData.hasOwnProperty(property)) {
        console.log(k);
        console.log(v);
        console.log(property);
        //$('input[name= k ]').val(v);
    }
}

On the inner loop you should be iterating v not retrievedData. On each pass of $each v will be an object.Try this:

$.each(retrievedData, function(k,v){    
    for (var key in v) {
        if (v.hasOwnProperty(key)) {
            console.log("key: " + key);
            console.log("value: " + v[key]);
        }
    }
});

You should do some type checking that v is an object first and catch any errors.

Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28
cortexlock
  • 1,446
  • 2
  • 13
  • 26
  • Thank you... that was completely hellish. And thanks everyone for all of the help. – user3697407 Jun 29 '14 at 07:51
  • To confuse matters, arrays in JavaScript actually are objects. But you shouldn't use for...in with them. Worth doing some reading around on this. Your post resonated as I remember undefined hell very well :) – cortexlock Jun 29 '14 at 08:29
1

Use either :

$.ajax({
   'dataType' : 'json'
});

Or

$.getJSON

Or if you want to use $.post, just do in your success function :

var good_data = JSON.parse(data);
$.each(good_data, function(k,v) {
   $('input[name= k ]').val(v);
});
Tanatos
  • 1,857
  • 1
  • 13
  • 12
  • I have been trying to use Parse. If I console.log(k + v) I just get 0[Object object]. Furthermore if i console.log(k); console.log(v); I get 0 and then the object. I need to get the key and values out of the object. – user3697407 Jun 29 '14 at 07:02
1

First you need to define you're expecting JSON in your POST request - http://api.jquery.com/jQuery.post/

Then you need to iterate through the response.

$.post('getstuff.php', { id : id } function(data){
  //Assuming you get your response as [{"id" : "1", "name" : "bob"}], this is an array
  //you need to iterate through it and get the object and then access the attributes in there
  $.each(data), function(item){
    $('input[name=' + item.name + ']').val(item.id);
  });
}, 'json');

EDIT

If you want to iterate over the properties of the objects returned, you need to put another loop inside the $.each

for (var property in item) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

More about it here - Iterate through object properties

EDIT 2

To address the solution you've posted. You've used the wrong variable names. Here's a working fiddle - http://jsfiddle.net/EYsA5/

var $log = $('#log');
var data = '[{"id" : "1", "name" : "bob"}]'; //because we're parsing it in the next step
var retrievedData = JSON.parse(data);

    for (var parentProp in retrievedData) {  //this gets us each object in the array passed to us
        if (retrievedData.hasOwnProperty(parentProp)) {
            var item  = retrievedData[parentProp];
            for (var property in item) { //this gives us each property in each object
                if (item.hasOwnProperty(property)) {
                    console.log(item[property]);
                    $log.prepend("<br>");
                    $log.prepend("Property name is - " + property);
                    $log.prepend("<br>");
                    $log.prepend("Value of property is - " + item[property]);
                    //do stuff
                }
            }
        }
    }; 
Community
  • 1
  • 1
JohnP
  • 49,507
  • 13
  • 108
  • 140
  • I understand that this would work. However what If i don't want to specify each item, such as item.name, item.id etc. What if there are about 10 different columns and I want a more general key and value iteration? – user3697407 Jun 29 '14 at 07:08
  • @user3697407 You just need to do another iteration inside the $.each loop if that's the case. I've updated the answer – JohnP Jun 29 '14 at 07:19
  • Thanks. Can you look at my updated question? I am getting 0 as my property. I still want to try and avoid using actual property names, is that possible? – user3697407 Jun 29 '14 at 07:20
  • @user3697407 It is, and that's what I've done. But you've used wrong variable names in your code so it's not referring to the right values. I've updated my answer with the fixed code. – JohnP Jun 29 '14 at 07:35
  • Thanks. I've copied and pasted your code, checked for errors, but I am getting no logs in the console. The if statement is returning false. – user3697407 Jun 29 '14 at 07:40
  • Actually nothing is happening in the for loop. – user3697407 Jun 29 '14 at 07:45
  • @user3697407 Sorry, that's my bad. I wasn't paying attention to what I was writing. I've cleaned it up and put up a fiddle to fix some typos. Everything should work now. – JohnP Jun 29 '14 at 07:49
1

Answering your question based on your comments on other answer. My assumption is you are getting data as JSON,if not you need to parse it,for that you can use JSON.parse(string).

Here I'm using Underscore.js

 var data=[{"id" : "1", "name" : "bob"}]
   $(data).each(function(ind,obj){
    var keys=_.keys(obj);   
            $(keys).each(function(i,ke){
                console.log(ke)
                console.log(obj[ke]);
           })
   });

Here is JSFiddle of working code

Ninad
  • 423
  • 2
  • 8