views:

51

answers:

2

I need to loop through a returned array in javascript but it doesn't work, it will loop through each letter of the word array instead of looping throught the value.

this is the javascript code

$.ajax({
        url: "<?php echo site_url('home/getsubcats'); ?>",
        type: 'POST',
        data: form_data,
        success: function(msg) 

        {
            for ( var i in msg )
            {
                alert( msg[i] );
            }
            //$('#main_content').html(msg);
        }
    });

and this is the controller (it get's the correct data so the query is not the problem);

        function getsubcats()
        {
            $this->load->model('site_model');

            if ($this->input->post('ajax')):
                $catid = $this->input->post('id');
                return $this->site_model->getSubCats($catid);
            endif;
        }
+2  A: 

You might have to add returnType: 'json' to your $.ajax option object if your code returns JSON.

If your code loops over single characters it means msg is a string and not an array.

Additionally, use for(var i = 0; i < msg.length; i++) as for in loops will also include inherited attributes - so when using javascript frameworks which extend Object.prototype or Array.prototype you might run into trouble.

ThiefMaster
+1 also `for`...`in` doesn't guarantee you get the items out in the right order. (And iterating strings or accessing `str[n]` is non-standard and doesn't work in all browsers either.)
bobince
I used the function json_decode() in the controller with the returned array from the model. That way I could get the values using json and in so doing update the dropdown :D thanks for putting me on the right path.
krike
A: 

You are most likely iterating on a string response, not an Array. I don't think jQuery makes the conversion automatically.

I'm not familiar with CodeIgniter, but when you return getSubCats(), is the result automatically encoded into JSON? Because if not, you must encode it before sending it to the client.

Use the net panel of Firebug or the Resources tab in Chrome to inspect the actual response.

Victor Stanciu