views:

948

answers:

2

Hello,

I have a website where I am wanting to get some query results through AJAX and JSON, but I have absolutely no idea how to do it, I have this function,

public function category() {
        $table = $this->uri->segment(2);
        $content_id = $this->uri->segment(3);
        $data['content'] = $this->site_model->get_content($table, $content_id);
        $this->load->view('template/right-content', $data);
    }

Essentially the query that is run is dynamic depending on what url is being passed, what I need to is, for the user clicks a link something like

<a href="/category/blog/1" id="blog">Read the blog</a>

From this link I get blog and 1 passed to the query, but I need to load the results in a view that is loaded in to my main template and then everytime a link is clicked do the same thing without overwriting the previous data, does anyone have any idea how to do this?

+1  A: 

If I understand you correctly, you need to send an Ajax request to that url and then append it to the appropriate place in your document. Something like this:

$("#blog").click(function () {
    var url = $(this).attr("href");
    $.ajax ({
        url: url,
        type: "POST",
        success : function (html) {
            $("#someDiv").append(html);
        }
    });
});

So that Codeigniter view should only contain the content, really, and perhaps some markup necessary to style it. The containers where the content goes should already be in the page where the link is originating.

Nate B
A: 

Or, if you want actually want your data to come back as JSON you could do something like this

public function category() {
        $table = $this->uri->segment(2);
        $content_id = $this->uri->segment(3);
        echo json_encode($this->site_model->get_content($table, $content_id));

}

AND, if you use the above authors method of using $.append, you'd want to modify your controller as such:

public function category() {
        $table = $this->uri->segment(2);
        $content_id = $this->uri->segment(3);
        $data['content'] = $this->site_model->get_content($table, $content_id);
        echo $this->load->view('template/right-content', $data, TRUE);
    }
Zack