php ajax call not working quite right

Javascript coding ..

Moderators: macek, egami, gesf

dot
New php-forum User
New php-forum User
Posts: 1
Joined: Wed Sep 19, 2012 7:17 am

php ajax call not working quite right

Postby dot » Wed Sep 19, 2012 7:24 am

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:

Code: Select all

<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>

Return to “JavaScript”

Who is online

Users browsing this forum: No registered users and 1 guest