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?
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');
}
I'd say an Ajax request is exactly the same as a non-Ajax one : it works exactly the same way, actually, from a point of view of HTTP Protocol.
The only difference is that you are returning some non-formated data, as JSON or XML (hey, this is the same as generating an ATOM feed ^^ ), or only a portion of an HTML page.
So, I would treat those as any other "normal" HTTP request, and place them the way I would for non-Ajax requests.
A semi-alternate idea might be to have only one action in your controlller : /browse/blogs -- and always call that one.
But, it would detect if it's being via an Ajax request or not, and would :
return a full page if called via a "normal" request
or return only some data (or a portion of the page) if called via an Ajax request
Note : that's not a "wild" idea ; Zend Framework, for instance, provides some stuff to facilitate that (see 12.8.4.3. ContextSwitch and AjaxContext )
Even though you're not using asp.net MVC, I'd recommend you look through the nerd dinner tutorial, specifically the AJAX section. it will help answer some of your design questions.
They have a separate action on the same controller.
http://www.wrox.com/WileyCDA/Section/id-321793.html
Related
I'm a semi newbie so please bear with me... Note, I don't know either jQuery or Json at this point
In my MVC project (I'm not using a framework but the project combines a front controller with an MVC), I have:
1) a Controller, which sends some parameters to a DAO. The DAO runs a MySQL query and sends back to the Controller an array of articles.
2) a View layer where I want the user to be able to click a button to move from article to article. The way I'm proposing to do that is by a javascript Ajax call to get the next article in the array generated in the Controller.
My question is: what should be the URL called by the Ajax function? Obviously it cannot call the Controller (or can it?). Should I add a class of dedicated Ajax content vessels that the Controller would instantiate with the array? I have difficulties seeing how the View would find the right URL... Should the Controller pass the parameters to the View and let it request the query?
The XHR (also known as AJAX) calls are no different at controller level, then classical browser requests. The difference is only in what you expect to receive in response.
This means that, if you have fully realized views (no just dumb templates), the type of request should be important only to the views. You can easily distinguish them by adding extensions:
http://foo.in/user/list - simple request
http://foo.in/user/list.json - XHR request
The difference gets recognized mostly at the routing mechanism, which them sets specific details on the Request instance. When controller sees that Request instance has a isXHR flag, it tells the view: "Respond to this with something, that is not full HTML page".
Basically, the same controllers should handle both the normal and XHR calls. In fact, you do not care about, what type of request it is. Only whether you need to produce html, xml or json in the response.
P.S.: model layer should be completely unaffected by the type of requests.
From the list of above posts I assume you must know the Ajax syntax to call a method while editing articles.
How to do so is as follows:
1. Initially define an action inside your controller which servers your purpose (May be editing your articles in this context.)
2. Through ajax method specify the Controller and the action which you wants to call. (
At this juncture it should be Articles -- Controller, EditArticle -- Action).
The control automatically navigates to the particular action method.
Regards
Pavan.G
Depends on the framework you use. But generally:
You can use the Controller with sending a "flag" (in a GET variable for example), that it is a AJAX query, and then exit the function, but having different Controllers for AJAX queries are considered a nicer route :) Anyways, something similar to this:
function page() {
if($_GET["is_ajax"] == "1") {
// return the AJAX query
return;
}
// go on with showing the page
}
Hope this helps!
I started using Ajax with Symfony2 and have some practise questions about it, especially the routing.
Over what HTTP-Method does Ajax send Requests (GET?) and which method is used to response (POST?)?
How should I design the routing for Ajax?
Is there on big ajax-route where the controller checks out what the client want and answers or are there a couple of different routes. Or are there even hybrid controllers who handle HTML and JSON requests?
You can send your request either by POST or GET. It is up to you.
There is nothing special with Ajax, neither different from normal routing design. Point your router to the controller you wish and handle request inside the function. In the end return data with JSON (which is my personal choice)
$return = json_encode($return);
return new Response($return, 200);
Should MVC Ajax requests be mapped the same way as regular requests in a MVC framework?
For example: Say I want to check and see if a username is available via ajax and have a method on a controller that performs this scope of work. Do I simply add a route that maps the ajax request to a particular controller method, or is there a better way to achieve this?
Thanks in advance.
When you are asking a ajax call to fetch data or information you pass the url to that page. But in case of MVC the url becomes controller/function_name. So in url of the ajax call it should be controller/function_name. And since this kind of request is handled by MVC you don't need to worry about it.
They use the same point of entry and flow.
Ajax or not, it's just an request needed of routing.
I thought of having an AJAX module service layer, with controllers and actions that interact with my model. Easy, but not very extensible and would violate DRY. If I change the logistics of some process I'll have to edit the AJAX controllers and the normal controllers.
So ideally I would load the exact same actions for both javascript and non-javascript users. I have thought about maybe checking for $_POST['ajax'], if it is set I would load a different (json'y) view for the data. Was wondering how/a good way to do this (front controller plugin I imagine?) or if someone can point me to an UP TO DATE tutorial that describes a really good way for building a larger ajax application.
You can actually use the request object to determine if a request has happened through ajax, e.g.:
// from your controller
if($this->getRequest()->isXmlHttpRequest()) {
// an ajax request, do something special (e.g. render partial view)
} else {
// render entire view
}
That's basically testing for the x-requested-with header (which is not always present, depending on JS library, etc). See (under the heading of 'detecting ajax requests'):
http://framework.zend.com/manual/en/zend.controller.request.html
You can check for XmlHttpRequest headers. Not all Javascript libraries do this, though, and even the ones that do don't necessarily do it in all browsers.
There's also AjaxContext, which basically checks the "context" request variable similar to your idea of $_POST['ajax'].
What I actually ended up doing was similar to your original suggestion. I created an AJAX module. In order to prevent tons of controller code duplication, I created a service layer that handles all the operations on models, so my controllers are really only responsible for transforming input requests and display.
I am using Kohana but this question applies to Rails, CI, or any other MVC web development framework. Where is the best place to stick one's server side AJAX scripts?
I was planning on creating an Ajax_Controller and using a method/action per individual script.
For example, a login form on the home page index.php/home would send an XMLHttpRequest to index.php/ajax/login, and the edit profile form index.php/profile/edit would send an XMLHttpRequest to index.php/ajax/editprofile. What's the best practice?
I tend to put my ajax actions in the same controller as the non-ajax actions for any given model.
When I can, I try to use the same actions and only change the output type. Most tasks should have a non-ajax version anyway, so this tends to work quite well. Very handy for reducing logic duplication.
AJAX crosses all of the MVC boundaries. That is, it doesn't go into just one of model, view or controller.
Your AJAX scripts will be calling scripts on your site - so this would involve a section of your controller layer which you've created for the purpose.
That controller in turn would access the database using the interface provided by your model layer, just as a non-AJAX request would.
The data for the response back to the client may be packaged as JSON or XML or something. Technically this is the task of your view layer, though if your application's definition of a view layer is nothing more than "an HTML templating system" rather than "processing and formatting anything that gets sent back to the client whether it's HTML or something else like XML" then your XML or JSON generation may need to go into a new little section of its own.
As for sending the scripts (Javascript files) themselves, this is probably going to be handled directly by the web server rather than from within your MVC framework.
Do you make different controllers for GET and POST requests? I don't. In my opinion, JS requests shouldn't be dealt with differently either.
I personally see JS requests just like GET, POST or any other type of request. So if I have user-related JS-based actions, I simply create them in the user controller.
If you mean the AJAX (Javascript) scripts themselves, these should go into your public/js folder. However, if you mean the actions invoked by these AJAX requests, they should be treated as any other actions of the respective controllers. To be completely RESTful, you should be using a different format (json, xml, etc.) as return values for those actions.
I am a noob, but based on my understanding, to achieve ajax with php mvc... thinking steps might be:
change the definition/function of the existing php view layer from 'HTML template' into 'results formatting (XML,JSON etc..' -> results from relevant module, which then called by controller to output into AJAX object, then it means you need to write view layers into each particular class with formatting methods
PHP module layer stays same
build a Ajax router class with JS which stay the same structure which you route in your PHP
build a ajax results handler class with JS to handle the results got back from PHP controllers (XML JSON etc..), then from here do whatever user interactions you want, this will be called by above Ajax router class
So,
ajax router (send XMLhttprequest)
-> PHP controllers C
-> PHP module -> PHP view results M
-> PHP controllers output results V
-> ajax results handle (into page)
I don't use Kohana but what I do in my framework is that AJAX scripts are controllers. I try to treat them as standalone controllers but in the end they are just controllers.
Using a separate controller is a good idea. I either organize my controllers by function and then actions by return type.
Additionally, when I'm using Pylons I can decorate an action with #jsonify and that will automatically take care of converting python objects to JSON. Very handy.
I like to keep all my ajax requests in one controller, typically dispatching their requests through a shared model (that the non ajax controller also uses)
The main difference being the view that results via the ajax controller (html fragments, json data, etc) or the non-ajax controller (full pages)
You could wrap it up as a general REST-api, and use RESTful conventions and URIs.
Example:
Instead of index.php/ajax/editprofile it could be a PUT request to index.php/api/profile/profilename.