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;
}
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
msgis a string and not an array.Additionally, use
for(var i = 0; i < msg.length; i++)asfor inloops will also include inherited attributes – so when using javascript frameworks which extend Object.prototype or Array.prototype you might run into trouble.