0

I have a php page which includes the following javascript:

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

what i'm trying to accomplish is dynamically show a combo box if the variable "returnDataFromController" has any items.

But I think I have a bug with the line that checks JSONdata.length.
Regardless of whether or not the ajax call returns a populated array or an empty one, the length always shows a being 1. I think I'm confused as to what is counted when you ask for the length. Or maybe my dataType property is incorrect? I'm not sure.

In case it helps you, the "console.log(returnDataFromController)" line gives the following results when i do get data back from the ajax call (and hence when the combo should be created)

[16:28:09.904] ({'2.5':"Admin1", '2.10':"Admin2"}) @ http://myserver/myapp/index.php/mycontroller/getbranches:98

In this scenario the combo box is displayed with the correct contents.

But in scenario where I'm returning an empty array, the combo box is also created. Here's what the console.log call dumps out:

[16:26:23.422] [] @ http://myserver/myapp/index.php/mycontroller/getbranches:98

Can you tell me where I'm going wrong?

EDIT:

I realize that I'm treating my return data as an object - I think that's what I want because i'm getting back an array. I guess I need to know how to properly check the length of an array in javascript. I thought it was just .length.

Thanks.

EDIT 2 : Maybe I should just chagne the results my controller sends? Instead of returning an empty array, should I return false or NULL?

        if (isset($buildingforbranch))
        {
                echo json_encode($buildingforbranch);  
        }
        else 
        {
            echo json_encode(false);
        }

EDIT 3:

Based on the post found at Parse JSON in JavaScript?, I've changed the code in the "success" section of the ajax call to look like:

                success: function(returnDataFromController) {

                        var htmlstring;
                        htmlstring="<select name='L2Locations' id='L2Locations'>";
                        htmlstring = htmlstring + "<option value='all'>All</option>";

                        console.log(returnDataFromController);


                         var JSONdata=returnDataFromController,
                            obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
                            alert(obj);
 }

But i'm getting an error message on

[18:34:52.826] SyntaxError: JSON.parse: unexpected character @ http://myserver/myapp/index.php/controller/getbranches:102

Line 102 is:

obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
Community
  • 1
  • 1
dot
  • 14,928
  • 41
  • 110
  • 218
  • 1
    JSONdata is not a string, length returns the length of strings. –  Sep 18 '12 at 20:42
  • 1
    I believe you should not put returnDataFromController into a array. Don't you really want "var JSONdata=returnDataFromController;"? (Without the []) – Matteus Hemström Sep 18 '12 at 20:42
  • you're creating an object when you put it in brackets, as opposed to a string. Also note the distinction between the property [.length](http://api.jquery.com/length/) (jquery) and the method [.length()](http://www.quirksmode.org/js/strings.html) (plain JS) – ernie Sep 18 '12 at 20:43
  • @Daagon, how do i check for the length of my return data then? that is, how do i check for an array that has more than 0 elements? – dot Sep 18 '12 at 20:44
  • @ernie, i do want an object... because its an array of items .... so i guess i just need to know how to check the length of an array in JS. I'll google that... – dot Sep 18 '12 at 20:49
  • 1
    you're creating an array of length 1, as the array will have the whole JSON object, not an array of the items in the JSON object – ernie Sep 18 '12 at 20:51
  • @ernie - ah! so should i just change the results i'm sending from my controller? Check out Edit #2 in my post – dot Sep 18 '12 at 20:54
  • See http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript to use the JSON directly, rather than trying to convert it to an array – ernie Sep 18 '12 at 21:02
  • @ernie, I've tried to modify my code to match the post you've listed. Please note EDIT #3 in my post. Thanks very much. – dot Sep 18 '12 at 22:40

1 Answers1

0

The problem was that the data from the controller is malformed JSON.

Note the part of my post where I show the return data:

  ({'2.5':"Admin1", '2.10':"Admin2"})

The 2.5 should be in double quotes not single quotes. I don't understand how / why this is happening but I will create another post to deal with that question. Thanks everyone.

dot
  • 14,928
  • 41
  • 110
  • 218