Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC ajax calls - where to handle them?

I have a self-rolled MVC framework that I am building, and up to this point have managed to avoid the need for any AJAX calls. Now, however, I'd like to create a real-time updating feed.

My question is, where are the handlers for the ajax calls usually stored in an MVC? Should I store them in the same controller that is involved in making the call?

For example, if my domain www.example.com/browse/blogs (browse is the controller, blogs is the method) is making an AJAX call for an updated list of blogs, would the call simply be to www.example.com/browse/update_list or something?

OR, so it be to a separate AJAX-only controller? www.example.com/ajax/update_blogs

How do you do it?

like image 272
johnnietheblack Avatar asked Jan 06 '10 22:01

johnnietheblack


People also ask

Why we use AJAX call in MVC?

It is a client-side script that communicates to and from a server/database without the need for a postback or a complete page refresh. The Ajax speeds up response time. In other words, Ajax is the method of exchanging data with a server, and updating parts of a web page, without reloading the entire page.

How write AJAX call in MVC?

As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features.

Which method is used to handle an AJAX request in the server side?

Two commonly used methods for a request-response between a client and server are: GET and POST.


1 Answers

Best practice would be to disregard the fact it's an AJAX request entirely and to only concern yourself with what controller your AJAX request is pertinent to. If you were to have a catch-all AJAX controller you'd likely be grouping apples to pears, so to speak.

The main difference is that for AJAX requests you will likely need to avoid setting any layout (and more than likely view) data. This can easily be remedied by having a method in your parent Controller class which checks for valid AJAX requests:

protected function isAjax()
{
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
            $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
}
like image 175
Corey Ballou Avatar answered Oct 04 '22 10:10

Corey Ballou