![]() |
Views, JSON, and HTML - 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: Views, JSON, and HTML (/showthread.php?tid=55787) |
Views, JSON, and HTML - El Forum - 11-09-2012 [eluser]luster[/eluser] I'm new to CodeIgniter and MVC. I'm having some trouble trying to figure out the best place to put a snippet of HTML. I know that the answer is probably in the View area. Here is the problem, sometimes I want the snippet of HTML to be called normally, but other times I need AJAX to call it and to return it as JSON. How do I accomplish this? On my webpage I have a "Add" button. This calls the Ajax and should return with some JSON that contains the HTML and the ID of the HTML. This seems like this should be a common thing that people want to do. How do I accomplish this? Views, JSON, and HTML - El Forum - 11-09-2012 [eluser]CroNiX[/eluser] Lots of ways really, but you could just have a method in your controller that you call with your ajax request and have it return that view. Code: function send_view($view = '') Then send your ajax request to http://yoursite.com/your_controller/send_view/view_name If you need to send extra parameters you can do that using POST ajax method and enter them there in the data portion and retrieve them with $this->input->post($field_name) in your "view_name" method where you can do what you need to do and pass them to the load::view() You could also send them as extra URL segments (instead of data in post) and have it automatically passed to the send_view() method like the example shows with $view. Views, JSON, and HTML - El Forum - 11-09-2012 [eluser]luster[/eluser] The problem is that: $this->load->view($view); just dumps the HTML to the screen. I need to put it in a JSON object and then download it. So something like this: {'html': '<h1>html here</h1>', 'id': 44} I want to reuse code here. Sometimes I just want to return the straight HTML and other times I want to put it in JSON and return it. How? Views, JSON, and HTML - El Forum - 11-09-2012 [eluser]CroNiX[/eluser] Code: function send_view($view = '') Views, JSON, and HTML - El Forum - 11-09-2012 [eluser]luster[/eluser] AWESOME! Did not know there was a third param for returning the HTML in the "view" function. Thank you so much! Views, JSON, and HTML - El Forum - 11-09-2012 [eluser]PhilTem[/eluser] [quote author="luster" date="1352506446"]AWESOME! Did not know there was a third param for returning the HTML in the "view" function. Thank you so much! [/quote] But the user's guide says so. Hence reading the guide may really be a pain in the you-know-where but it will save you some "bad experiences" ![]() |