raviolican raviolican - 4 months ago 29
Ajax Question

AJAX Call in MVC Structure PHP

i have an AJAX featured page for dynamic rendering. I wondering how to handle an ajax call in MVC. The first idea I had was to create a new controller for ajax calls without rendering views and check in the routing for an ajax request like this

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
call_user_func_array(array("ajax", $this->url_action), null);
}


I'm just doing my 1st mvc, is there a better way to handle ajax?

Kind Regards

Answer

I would let the location of AJAX handling code depend on its context. If it is handling the same kind of content as another controller that returns a full view, just make an "ajax method" in that controller, that responds with for instance a JSON header, the contents you want to send to the browser and exits. Not really a need for a dedicated AJAX controller, just like you don't have a separate GET controller or POST controller.

EDIT: (an example)

class BookController
{
   public function getBookDetail($id)
   {
       // Go fetch a book from the DB.
       // Assemble your full fledged view
       // Send it to the browser
   }

   public function ajaxBookDetail($id)
   {
       // Go fetch a book from the DB.
       header('Content-Type: application/json');
       echo json_encode($someBookData);
       exit;
   }
}

You can then tell your router to use the ajax-prefixed method instead of the get-prefixed one, if you detect xmlhttprequest in the SERVER headers.