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.
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'm new to the OOP paradigm (and AJAX/jQuery), but would like to create a basic site employing MVC architecture, in PHP, with AJAX functionality. I drew up a brief diagram of how I currently 'understand' the architecture.
Presumably when AJAX is used, that acts as the controller to interact with the model directly to retrieve whatever functionality is needed? The filenames I added are just to give you an idea of what I 'think' should be included. e.g. index.php would be a html/css template with includes to modules in the relevant places (whatever they may be) - news.php, navigation.php, etc. database.php/pager.php might house the classes and extended classes that I create for pagination, or connecting/querying the database I'm struggling to see what the controller component could be - it'd surely end up being a 'second back-end view' - calling the classes from the model to be sent to the view?
I've probably portayed my confusion well here - what should go in the view, controller and model... is AJAX functionality technically another controller? Any diagram similar to my one above would be extremely helpful.
OK so AJAX is a transport method and not a piece of application like a model or controller.
Your client will communicate through AJAX with one or more Controllers.
These Controllers use or invoke Models to handle different kind of tasks.
Then either the controller or the model responds to the request either with a message in a transport-friendly format (JSON, YAML, XML) or with a View (piece of HTML).
The controller handles requests, that means it receives the initial client-input. Depending on the situation this input has to be formatted, normalized, mutated or transformed somehow before being used in your application.
Then a controller uses or invokes a model; this means that it either deals with business logic itself (old style) and makes use of the model to access datasources or it hands the main workflow of your application completely over to the model (new style).
A model in first instance abstracts a persistent storage entity (like a database). In contemporary application design it also does the main business logic of your application.
There's one way to see this.
Ajax is the medium for sending data between MVC components like HTTP POST. In this respect it does not show up in the MVC pattern.
The actual display in JSON format can also be seen as a view if it's actually used to show data.
From this you should be able to come to your own conclusions.
You can use PHP's best MVC architecture called "YII".Get more info from here
http://www.yiiframework.com/
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'm building a webapp in MySQL/PHP/Javascript.
In PHP, I've got all the classes from the domain od the problem which persist in the database.
In Javascript, there is a cache with objects from the last queries.
When an object in Javascript is updated by the user, it has to update itself in server-side. Which would be the best way to do this?
Should I create a class in PHP and Javascript for communication purposes? Should each object in Javascript send an AJAX query to a different php file depending on the class of the object it needs to update?
Are there any patterns to follow to solve this?
Creating a separate PHP file for each class would certainly be more maintainable if this is a project of any size at all. It would also allow you to do things like have different server-level authentication based on the classes.
On the JavaScript side, you definitely want some sort of AJAX library, whether you throw it together yourself (I did one once in about 50 lines of JavaScript) or use one of the ones out there. You may need a helper function or two that knows how to serialize the data (XML, JSON, delimited, whatever).
You can write object oriented code in JavaScript, and if you're doing that already, it makes sense to add a write() or updateServer() method to call the AJAX library with the right parameters for consistency. If you're not writing OO code, it still may make sense to have separate functions, but only if there's more than one place you need to persist these objects from.
Most AJAX frameworks (jQuery etc) will send an 'HTTP_X_REQUESTED_WITH' header set to 'xmlhttprequest'. I like to use this to decide which view to use.
This means the same url can be used to retrieve JSON, XML, or HTML snippet via JavaScript or to return a full document if a standard GET / POST request is made.
This means your app will simply revert to normal requests should the user have JS disabled.
I think you should have a look into the RESTful API with PHP and JavaScript. You address your domain model objects as unique resources (e.g. /application/books/1). If you only want to implement CRUD functionality a generic Controller that updates the corresponding domain model (e.g using an ORM tool like Doctrine) should be sufficient.
If you really want to have the same model on the client side in JavaScript depends on your Application. I like the idea of just managing a single JavaScript object on the client side which will be loaded via REST and then populated to HTML Forms and send back e.g. as JSON (or as a simple form submit) to the server. If the client side model idea appeals to you, I recommend to have a look at JavaScript MVC which has a quite interesting model implementation.
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