Steve
Steve

Reputation: 3046

CodeIgniter return data from controller

I'm using CodeIgniter for a project I'm working on.

I have an ajax call in a view like this:

$.ajax({
    type: 'GET',
    url: 'extra/search/infojson/' + $(this).text().replace(/\s/g, "+");
    success: function(data) {
        /* Do something with that data */
    }

});

infojson is a method in a controller that takes a parameter of 'username', does a search, and will return a JSON object. Is there any way I can return this data without having to create another view for it? This method will only be used to return such data from this one page, so I can't see why I need to create another view just for that. I've read about _output() but it didn't make any sense to me.

Upvotes: 2

Views: 4436

Answers (3)

Steve
Steve

Reputation: 3046

This was the answer:

Put $this->config->set_item('compress_output', FALSE); just before the echo to disable output compression.

Source: http://codeigniter.com/forums/viewthread/155810/#784452

Upvotes: 4

Deepak
Deepak

Reputation: 6802

If you are compressing the output in your configuration file try to set $config[‘compress_output’] = FALSE;

Upvotes: 1

Jordan Arsenault
Jordan Arsenault

Reputation: 7388

Of course.

Return the data using PHP's json_encode() function, there is no need to call $this->load->view('someview', $data); to send data back to the browser on ajax requests.

class Extra extends CI_Controller{
    function __construct(){
        parent::__construct();
    }

    function search($username){
        $results = your_search($username);
        echo json_encode(array("results" => $results));
    }
}

And your jquery:

$.ajax({
    type: 'GET',
    dataType: "json",
    url: 'extra/search/infojson/' + $(this).text().replace(/\s/g, "+");
    success: function(data) {
        if(data.results){
            /* Do something with the results */
        }
    }
});

Upvotes: 1

Related Questions