Welcome Guest, Not a member yet? Register   Sign In
Views, JSON, and HTML
#1

[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?
#2

[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 = '')
{
  if ($this->input->is_ajax_request() && $view !== '')
  {
    $this->load->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.
#3

[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?
#4

[eluser]CroNiX[/eluser]
Code:
function send_view($view = '')
{

  if ($this->input->is_ajax_request())
  {
    $data['view_html'] = $this->load->view($view, array(), TRUE);
    echo json_encode($data);
    exit;
  }
  else
  {
    $this->load->view($view);
  }
}
#5

[eluser]luster[/eluser]
AWESOME! Did not know there was a third param for returning the HTML in the "view" function.

Thank you so much!

#6

[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" Wink




Theme © iAndrew 2016 - Forum software by © MyBB