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);
Related
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 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
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.
I've been researching PHP frameworks as of late for some personal projects, and it looks like most of them use a front controller to mimic a response. The controller gets the params from the request, and re-routes by sending the appropriate headers depending on the logic. This is the "response". Is this the best way to do this in PHP, or are there other theories about how to handle re-routing and responses?
a front controller lends itself quite well to a web environment, allowing you to funnel all requests to your application. since HTTP is stateless, and a user can, in a sense, inadvertently stumble upon parts of your app by accident (ie, hitting random URL's), a front controller allows you to determine the entry point of your application, and respond appropriately.
edit: in response to the comments, i think the confusion may be that java has a lot more structure to it than PHP, which might be overcomplicating the whole thing? ultimately PHP can provide for the very basic interaction from request to response:
switch($_GET['page']) {
case "one";
print "page one!";
break;
default:
print "default page";
break;
}
and from there you can layer in all sorts of things to front controllers passing request objects down a filter chain to a page controller which reroutes to the appropriate model which grabs data via your db abstraction layer, filters it, back up to the controller, and on to the view which constructs the appropriate response, all the while firing off random event hooks. ultimately it's up to you (as developer) to choose what level of complexity/separation you're looking for. this is both the beauty and evilness of PHP :)
I think you are confusing an Http response with a response object in the frameworks you looked at. A front controller is the gateway for your application - all (http) requests go through it, and it routes to the appropriate controller/action. Processing a request does not necessary results in a returned response (often requests are only meant to send information to the server), however all requests would have passed through the Front Controller.
A request object is often used to encapsulate the environment and http request parameters and provide an API to retrieve them. Its complement, the response object, is often used to encapsulate the process of generating an http response, including the generation headers.
There are other approaches to handling requests and routing, which are not unique to PHP (and neither is the front controller), such as a Page Controller, or not using an MVC structure at all.