trying to get an ajax call to work.
I'm just new to ajax and I'm having some trouble getting results to display when the controller is returning an emtpy array.
What I'm trying to accomplish is to display a combo box when the user clicks on a control called L1Locations.
If it's an empty array, I don't want to display a box at all. But right now, it always displays a combo box.
Can you tell me where I'm going wrong?
the output i get from my controller looks like this:
({'2.5':"Admin1", '2.10':"Admin2"})
and where it's an empty array,
the data is simply:
[]
Here's the code:
<script>
$(document).ready(function(){
$('#search').hide();
});
$('#L1Locations').live('change',function(){
var htmlstring;
$selectedvalue = $('#L1Locations').val();
$.ajax({
url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
type:'GET',
dataType:'json',
success: function(returnDataFromController) {
alert('success');
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=[returnDataFromController];
alert('string length is' + JSONdata.length);
if(JSONdata.length > 0)
{
for(var i=0;i<JSONdata.length;i++){
var obj = JSONdata[i];
for(var key in obj){
var locationkey = key;
var locationname = obj[key];
htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
}
}
$('#l2locations').html(htmlstring);
}
else
{
alert('i think undefined');
$('#l2locations').html('');
}
}
});
$('#search').show();
});
</script>