K.K. Smith
K.K. Smith

Reputation: 992

Can't seem to return JSON in Codeigniter

On a hover event over a single item in a gallery I want to populate an info window with results from an AJAX call. I'm new with CI and I can't seem to figure out why I can't make that work. I have checked other posts.. no love.

Can anybody point my error out to me?

Here is my javascript function firing on a hover

function showDataWindow(){
    $.post('index.php/home/getMoreInfo', { ID: thisID},
        function(data) {
             var moreInfo = $.parseJSON(data);
             alert(data); // just checking
             .. build my HTML with results and fade in ..
});};

Here is the relevant method in my controller

public function getMoreInfo()
{
    $answer = "unsigned";
    $ID = $_POST['ID'];
    $this->load->model('Artist_model');
    $assocReturned = $this->Artist_model->get_more_info($ID);
    echo json_encode($assocReturned);
}

And here is my Artist_model

public function get_more_info($ID)
{
    $query = $this->db->query("SELECT * FROM NOIRusers WHERE UID=$ID");
    $assoc = array();

    foreach($query->results() as $r) // there should be only one result .. do this different?
    {   
        $assoc['memberID'] =$r['UID'];
        $assoc['firstName'] =$r['UFname'];
        $assoc['lastName'] =$r['ULname'];
        .... a lot more like this ...
    }
    return $assoc;
}

I keep getting a 500 (Internal Server Error). I've got my Database library loaded btw.

I think the problem is how I am handling my database response. As I understand it .. $this->db->query() gives me a database object, which I then iterate into an associative array through the foreach. I return that array to my controller which then json_encodes it and echoes it back to javascript.

What am I not getting right?

Upvotes: 0

Views: 1927

Answers (2)

Brendan
Brendan

Reputation: 4565

I would give credit to Zathrus for pointing out GZIP compression as the cause.

In CodeIgniter, you cannot output directly from a controller with GZIP compression enabled. The reason for this is because the output class gets interrupted. To avoid this issue, do something like the following:

In your controller:

$data['json'] = json_encode($assocReturned);
$this->load->view('json', $data);

In views/json.php (or whatever view you make):

<?php echo $json;

I realize you've already solved your issue and it wasn't related to GZIP compression, but should you eventually optimize your site and enable it in CI, you will run into this issue if you keep your code the way it is.

Upvotes: 4

Zathrus Writer
Zathrus Writer

Reputation: 4331

Do you have error reporting turned on in CI? That should tell you what't wrong.

It can also be a wrong .htaccess file.

Or - if you're using GZIP compression, it will cause problems if you try to echo things out yourself. CodeIgniter uses views that are compatible with its gzip outputting - echo will break the page and fetch you a 500 error.

Upvotes: 2

Related Questions