1

Ok, I'm sure this is simple but I'm not jquery expert. I have an ajax call that has an array returned as a variable. I'm having trouble accessing that array.

Here is what I want to do.

My array is setup so that the key matches the id of an input on my page. I want to traverse through my inputs and if there is a key that matches the id of the input, set the value of that input to the value of what's in the array. So here is what I have so far:

function populateFields(table_name, user_id, div){
    $.ajax({
        data:{
            mode:'getInfo',
            table_name: table_name,
            user_id: user_id                            
        },
        url:'my_page.php',
        type: "POST",
        dataType: "text",
        success:function(data){
            data=$.parseJSON(data);
            if(data.error != undefined){
                if(data.error !== false){
                    showError(data.error);
                } else {
                    var inputName="";

                    $('#'+div+' > input').each(function(){
                        inputName=$(this).attr('id');
                        /*Check to see if inputName is a key and if so, set the value of this input to the value matching the key*/
                    });
                }
            } else {
                showError('The script was not called properly, because data.error is undefined.');
            }
        },
        complete:function(){

        }
    });
}

The name of the variable being returned is called info. So data.info is the object with the information.

In the debugger data.info has this setup:

Object
2: Object
  agreed:"no"
  city: null
  email: "email@email.com"

Any idea what the code would be between the /* */ marks?

Jacob
  • 77,566
  • 24
  • 149
  • 228
tomjung
  • 715
  • 3
  • 11
  • 34

1 Answers1

2

Note: there are some caveats to using Object.hasOwnProperty() See https://stackoverflow.com/a/136411/940754

Not sure why your data.info variable is coming back with the '2' key, but try:

// check to see if input name is a key
if(data.info[2].hasOwnProperty(inputName)) {

    // set the value
    $(this).value = data.info[2][inputName];
}
Community
  • 1
  • 1
Rick Suggs
  • 1,582
  • 1
  • 15
  • 30
  • I want to thank everyone for their help. This was it. I couldn't figure out why the data.info[2] is the array but I think it has something to do with how I'm passing it from my ajax page. Here is the code: `$info = $db->select('*', $_POST['table_name'], $where);` then I'm passing it back with ` echo json_encode( array( "error" => $error, "info" => $info) );` I think perhaps because I didn't turn $info into an array before passing it back? – tomjung Jun 21 '13 at 17:10