Thursday, March 13, 2014

'Returning' views as JSON(?) data via Ajax call

I'm not sure whether what I'm trying to do is possible, but here goes! I have a page with a search box on it. When the user searches, 2 separate areas of the page should be re-rendered. Rather than doing this by refreshing the page, I want to do it via an Ajax call. One of the rendered areas is a Google chart, so I also want some data back to set that up.

Normally if I'm doing this via Ajax, I'd only have 1 page area to re-render, so I'd just make the Ajax call, and then in the controller I'd have $this->render('whatever'); - this returns the contents of the area and then I do a javascript replaceWith to put it in place.

In this case, though, I need to get 2 separate areas back, plus some data. In theory I can do 2 separate Ajax calls, but that means running the search criteria twice, so I thought it would be more efficient to do the search once and return the two views in one go.

So I'm thinking I need to do something like this:
$return = array();
$return['view1'] = $this->render('area1');
$return['view2'] = $this->render('area2');
$return['data'] = array_of_data;

Then JSON-encode it and return. However, since 'render' actually displays the data, it doesn't really return an object that I can put in an array.  Is what I'm trying even possible?!

Thanks!

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: