0

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.

2 Answers 2

1

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);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Actually it was an element I wanted to use. So to do it you use $this->render() action and the rest is the same as you said, thank you
0

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/

2 Comments

Yes, I know I can do this but I want to use the conventions of CakePHP to make my work easier, just setting an data array to the element and it displaying properly
Also I'm not talking about a DOM element, I revised my question, I'm talking about a CakePHP view element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.