3

I have a codeigniter application returns some data from my database to a view. I'm trying to send it back as json data.

The problem is that the data that is returned it malformed. it looks like this:

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

When I test this on jsonlint.com, it shows that this is not valid json. the '2.5' should be in double quotes, not single quotes. What I don't understand is that I'm calling json_encode on my data before I pass it to the view. My code in my controller looks like this:

public function getbuildings()
{

        $buildings = array();
        $branchID = $this->uri->segment(3);
        $buildingforbranch = array();
        $_locations = $this->racktables_model->get_locations(); 
        //print_r($_locations);

        foreach ($_locations as $location)
        {
            if ((isset($location['L2FullID'])) && (!array_key_exists($location['L2FullID'],$buildings))) {
                $buildings[$location['L2FullID']] = $location['L2Location'];            
            }
        }

        foreach ($buildings as $key => $value)
        {

            $pattern = "/(".$branchID."\.\d)/i";            
            if (preg_match($pattern,$key))
            {
                $buildingforbranch[(string)$key] = $value;
            }

        }       
        header ('Content-Type: application/json; charset=UTF-8');
               echo json_encode($buildingforbranch);  

}

As you can see from the code, I've even tried casting $key explicitly to a string data type. But that doesn't seem to change anything. Any suggestions? Thanks.

EDIT 1

When I do a var dump on $buildingforbranch right before the header / json_encode() calls, I get the following results:

array(3) {
  ["2.5"]=>
  string(7) "Admin 2"
  ["2.10"]=>
  string(7) "Admin 1"
  ["2.11"]=>
  string(3) "SB4"
}

It looks good here ... but when I do a console.log() and pass in the data from the controller, the browser shows the incorrectly formed json data.

EDIT 2 Here's what i'm trying to accomplish. I need to dynamically create a combo box when a user clicks on a control on my page. If the ajax call results in an empty array, I don't want to display the combo. Otherwise, I try to populate the combo box with the results of the ajax call. Everything is working, except for the part where I'm attempting to check the length of the json data. My app always displays a combo box regardless of what is sent back.

Here's the code:

$.ajax({
                        url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
                        type:'GET',
                        dataType:'json',
                        success: function(returnDataFromController) {
                               console.log("getbuildings ajax call successfull");
                                var htmlstring;
                                htmlstring="<select name='L2Locations' id='L2Locations'>";
                                htmlstring = htmlstring + "<option value='all'>All</option>";

                                //console.log(returnDataFromController);
                                 var JSONdata=[returnDataFromController];
                                 console.log(JSONdata);
                                 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>";
                                                    } //end inner for


                                                $('#l2locations').html(htmlstring);

                                        }//end outer for
                                    }

                                    else {
                                        //alert('i think undefined');
                                        $('#l2locations').html('');
                                    }

                            }//success


                    });//end ajax

If I call the page that is returning the json data directly, i get [] as the result for an empty array.

dot
  • 14,928
  • 41
  • 110
  • 218
  • What does a `var_dump($buildingforbranch);` output if you drop it right before the call to `json_encode`? – Sean Bright Sep 19 '12 at 18:49
  • @Sean, check out Edit #1 in my post. It seems like it's ok when i print from php. but when i do a console.log($datafromcontroller), the browser shows the malformed key. ?? – dot Sep 19 '12 at 19:00
  • 1
    I wouldn't trust the output of `console.log`. If you navigate to the page directly with your browser (i.e. `http://mysite.com/app/page-that-returns-json.php`) that returns the JSON, what is the exact content? – Sean Bright Sep 19 '12 at 19:05
  • it looks correct. So if my data is not malformed... then I can't figure out why my code is not working. Check out edit number 2.. I'll add in a sec. – dot Sep 19 '12 at 19:07
  • I can't recreate a scenario where there are single quotes around the numbers. it's not `json_encode` – Phil Sep 19 '12 at 19:12
  • what is the exact result when you are navigating to `http://mysite.com/app/page-that-returns-json.php` using browser? – haynar Sep 19 '12 at 19:30
  • @haynar, that would be the contents under EDIT 1 – dot Sep 19 '12 at 19:37
  • under EDIT 1 is the result of `print_r` and not `json_encode`. anyway I am a little confused about this line: `var JSONdata=[returnDataFromController];` why do you need square brackets here? – haynar Sep 19 '12 at 19:40
  • @haynar, my bad. here's what you originally asked for : {"2.5":"Admin 2","2.10":"Admin 1","2.11":"SB4"} – dot Sep 19 '12 at 19:46
  • @haynar, I thought the [] around the variable would explicitly defined it as an object instead of a string....?? – dot Sep 19 '12 at 19:46
  • ´here's what you originally asked for : {"2.5":"Admin 2","2.10":"Admin 1","2.11":"SB4"}´ so json_encode is creating good JSON data with double quotes – Saic Siquot Sep 20 '12 at 19:51

3 Answers3

0

[] is actually defines an array with a single element in your particular case. But as I see you are using jQuery ajax with dataType: "json", this means that the returned value is already an object, you don't need to parse it one more time, so just remove []:

var JSONdata=returnDataFromController; // instead of var JSONdata=[returnDataFromController];
haynar
  • 5,961
  • 7
  • 33
  • 53
  • when i remove that, the combo box is not created at all, even for calls where the controller is returning data. (as an aside, the console.log is still showing single quotes around the key values instead of double quotes). – dot Sep 19 '12 at 20:15
  • @dot what is the result of `console.log(typeof(returnDataFromController))` ? – haynar Sep 19 '12 at 20:23
0

As stated in your other question, you need to handle the JSON as JSON.

Basic overview is:

  • returnDataFromController will be a string, use JSON.parse() or jQuery's parseJson() to convert it to a JSON object
  • Rewrite your loop that generates the options to iterate over a JSON object, instead of an array. Note that jquery.each() can handle both arrays and objects will handle This appears to be the part that you're missing . . .

The real key here is keeping datatypes straight. You're getting a string back, that contains JSON data. There's no easy way to convert that to an array, so read it in as JSON. Since it's now a JSON object, you have to treat it as a JSON object, not an array.

Check the jQuery Utilities category for other JSON related items.

Community
  • 1
  • 1
ernie
  • 6,356
  • 23
  • 28
0

Use firebug on firefox to see what is shown in "response" tab on "net" tab
This code

<?php
echo json_encode(array(
  "2.5"  => "Admin 2",
  "2.10" => "Admin 1",
  "2.11" => "SB4"
));

produces this output {"2.5":"Admin 2","2.10":"Admin 1","2.11":"SB4"} on my server (php5.3) and on this fiddle example http://www.phpfiddle.org/main/code/xqy-ize

Saic Siquot
  • 6,513
  • 5
  • 34
  • 56