CodeIgniter Forums
Returning view partials using AJAX and JSON - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Returning view partials using AJAX and JSON (/showthread.php?tid=10974)



Returning view partials using AJAX and JSON - El Forum - 08-20-2008

[eluser]mattalexx[/eluser]
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:
Code:
{"partials":{
   "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?


Returning view partials using AJAX and JSON - El Forum - 08-20-2008

[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:

Code:
$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.

Randy


Returning view partials using AJAX and JSON - El Forum - 08-20-2008

[eluser]mattalexx[/eluser]
Hey, cool! I didn't know load->view returned the content as well.

Thanks.


Returning view partials using AJAX and JSON - El Forum - 08-20-2008

[eluser]moksahero[/eluser]
you have to set the third parameter to TRUE not second one as in the example above.

http://ellislab.com/codeigniter/user-guide/libraries/loader.html


Returning view partials using AJAX and JSON - El Forum - 08-20-2008

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

Thanks.