• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Returning view partials using AJAX and JSON

Okay, so I've been looking around for a solution to this problem for a while but I haven't found it.

Here's an example of the desired functionality: In a DIV tag with the ID of "big_image" is a big image of the product. In a DIV tag with the ID of "item_image_thumbs" are a few thumbnails of alternative views of that item. When the user clicks one of the thumbnails, an AJAX request is initiated. Server-side, some data is saved into the session that basically says, "Show item image 143 as the large image for item 64". So far, so easy. Now I need the AJAX to return HTML for both of the included DIVs. The "big_image" DIV needs an updated big image. The "item_image_thumbs" DIV needs a new list of thumbnails, with a darker border around the selected one.

I need to have the original AJAX call return a JSON array like the following:
   "big_image":"{HTML FOR big_image DIV}",
   "item_image_thumbs":"{HTML FOR item_image_thumbs DIV}"
With a JSON like this, I could easily write a general JS function that updates the DIV with the HTML present in the array.

Here's my question: In the controller, how do I load partial views into variables so that I can encode them into JSON and print them? What would be the best way to do this?

[eluser]Randy Casburn[/eluser]
Hi Matt,

There are numerous ways...and accompanying opinions ;-)

If the HTML exists in view partials, load the view partials into a variable as you normally would:

$big = $this->load->view('HTML FOR big_image DIV',TRUE);
$thumbs = $this->load->view('HTML FOR item_image_thumbs DIV',TRUE);

$aPartials = array('partials'=>array('big_image'=>$big,'item_image_thumbs'=>$thumbs));

echo json_encode($aPartials);

and there you have it.


Hey, cool! I didn't know load->view returned the content as well.


you have to set the third parameter to TRUE not second one as in the example above.


[eluser]Randy Casburn[/eluser]
Whoops...thanks...too quick on the keys.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.