1

I am using CakePHP and using MVC standards.

I am sending a request using ajax and need a response in the same manner as tweeter response, see tweeter sample response below.

Like tweeter sends:

{
"user_id":"155dsfds95",
"html":" \u003Cdiv class=\"module profile-card component profile-header\" data-component-term=\"profile_follow_card\" \u003E\n ",
"screen_name":"abc"
}

I need to send user_id and screen_name from controller and html content from view.

my response data is as follow:

$response['user_id'] = $id;
$response['screen_name'] = 'some_name';

As of now I can send user_id and screen_name as json_encode($response)

But how do I send view content also in data index with the response?

UPDATES

I do not want to make html content in controller, rather it should come from view.

4
  • Are you asking how you get a rendered view within a controller? Commented Jan 8, 2013 at 14:45
  • Hello jeremyharris, I do not want to make html content in controller due to MVC contraints. How to achieve this like tweeter. Commented Jan 10, 2013 at 4:59
  • Have you looked at JSON Views? book.cakephp.org/2.0/en/views/json-and-xml-views.html - assuming you are in CakePHP 2 Commented Jan 23, 2013 at 10:43
  • Yes david, i have looked at JSON Views, but in json/XML views also, we can only manipulate data coming from controller. What i need is send view content in one json key along with another json key created at controller. Commented Jan 25, 2013 at 7:01

1 Answer 1

1

You can easily render the current view from your controller and return a JSON response with it.

Working example:

public function index() {
    $response = $this->render();
    $data = array(
        'json_key_1' => 'value1',
        'json_key_2' => 123,
        'action_html' => $response->body()
    );
    $options = array(
        'type' => 'json',
        'body' => json_encode($data)
    );
    return new CakeResponse($options);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for responding so late, this answer didn't come to my notice and today i accidently seen the answer, when i once again needed for this kind of functionality. +1 and accepting this answer. thanks

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.