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!
Related
In zend I'm interested in passing data from one controller to a view in another controller.
For example, I have a search controller whose purpose is to use the search model to query SOLR, and I want to have Index Controller call it from the view (via ajax or other means) and have Search controller return data to that view. Is that feasible? And is there a better way to do it?
Thanks in advance.
If you want to do it by AJAX, then you just need to have your client-side script (javascript, I'm guessing) initiate a request to the url corresponding to the search you wish to perform. You'd probably configure the search controller/action to use a context-switch so that it delivers the results in a format (json or xml, I'm guessing) in a format consumable by your client-side code.
The downsides to this approach include: making two full requests, including the HTTP overhead, to get the data; you'll get nothing for clients without js.
An alternative is let the index view-script call the Action view helper - called using $this->action($action, $controller, $module, $params) - to get the data directly. Again, you might wish to employ a context-switch or a param flag so that you don't deliver the HTML for the full site layout, but only that of the search results.
Finally, you could push that search functionality down into a service class so that both the Index controller and the Search controller can avail themselves of it independently. Then the controller just assigns those results to the view in the normal manner.
Personally, I tend to go for the service approach.
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 learning the PHP MVC pattern for my backend implementation. Looking at this excellent example:
Implementing MVC in PHP: The Controller
http://onlamp.com/pub/a/php/2005/11/03/mvc_controller.html
I feel comfortable with the execution flow in a GET.
But there is no mentioning of what happens in a POST. What would the typical controller code for the POST do? I wonder if I am misunderstanding something obvious here, since I can't find similar situations in previous SO posts or Google.
For example: An app to manage persons,(name, last, age) wants to add a record to db when a POST hits the controller.
What happens next?
My guess is that the 'View' is not used at all, or maybe for confirmation?
Is there just a call from the controller to a model class that adds a record to db?
Or do I skip the controller altogether for a POST and go directly to an "add record" script?
Is there any available example?
Thanks in advance,
Ari
Well, POST is basically the same as GET, just some random chunks of info client sended to server. So you can treat it the same way.
I worked with CodeIgniter MVC framework in PHP. It uses GET URI to route to controller and it's methods. When the POST request comes, it treats its URI in the same way. The later actions are in the hand of the programmer, who accesses POST request data directly or through some wrapper, and he can also don't use it at all.
I need to say that you focus on the wrong parts. MVC is not the model of everything, and it doesn't say how to treat POST or GET requests. It's just a simple principle known many years before the name "MVC" became famous as the principle about splitting of logic, data and representation. And most of software(from old to new) actually do this splitting, because it is very hard not to do this in most cases. In some apps the borders are not so evident, some of them even haven't object model. The implementation of the app is always up to you, because MVC doesn't say you what to write but just gives some clues about highest level organization of you code.
P.S. Sorry for my bad English.
Typically, the controller would process the request (the controller processes ALL requests), then call into the model to actually manipulate data based on the request, and then either redirect to somewhere else (triggering a new GET request), or invoke a view to output a resulting page.
Well, if you are going to build your own MVC pattern solution, you could make one tricky thing. Since you're handling MVC you're supposed to have a really reliable routing manager. So after parsing your URL and defining what controller/method you are supposed to trigger, you could make something like:
<?php
...;
$method_name = (count($_POST) > 0) ? "post_".$route_result : $route_result;
...;
and later in your controller class you could do something like:
<?php
namespace Controllers;
class MyController extends \System\Controller {
function my_method($whatever = null){
...;
return $this->view($model_or_whatever); // supposed that you prepared view Class in routes
}
function post_my_method($whatever = null){
...;
return $this->view($model_or_whatever); // supposed that you prepared view Class in routes
}
}
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.