8vius
8vius

Reputation: 5836

CakePHP - Setting data retrieved from AJAX call to element

I'm making a new data entry through AJAX. It consists of the model data and some HABTM data as well. I return all this data as a json object from my controller and I would like to add a CakePHP view element containing this data to the current view, somewhat what twitter does when you post a tweet.

How can I manage to get the json object, append the element and set the data from the json object to said element? I have a good idea about how to append the element but the data setting I'm not clear about.

Upvotes: 0

Views: 2007

Answers (2)

RichardAtHome
RichardAtHome

Reputation: 4313

If I'm understanding your question correctly, you want to use CakePHP views to display the results of the JSON data?

If so, you can do it like this:

In your controller:

function my_ajax_action() {

   $data = // whatever method you use to fetch your data
   $this->set(compact('data'));
   $this->layout('ajax');

}

Create a view file: my_ajax_action.ctp which outputs the formatted $data array

Use ajax to fetch back the HTML not the JSON <- important bit and insert it into the DOM:

$.ajax({
    url: '/controller/my_ajax_action',
    success: function (result) {
        $('#myelement').html(result);
    }
});

Upvotes: 1

Eriksberger
Eriksberger

Reputation: 191

Use $.getJSON to get the JSON, and then iterate and set the values on your page. Very straight forward..

Have a look here http://api.jquery.com/jQuery.getJSON/

Upvotes: 0

Related Questions