jQuery ajax with Codeigniter - codeigniter

JQuery’s AJAX “.get” method calls a (php page)method of a controller and the returned data is further processed….but then as we consider it a best practice, controllers are meant to just transfer control to the models and views..A controller never returns anything or echoes any data…so how can we support this argument? I may be wrong..still in the initial learning stages so pardon me if you find the question a bit too naive :(.
One eg. is JQuery’s autocomplete plugin that I was trying to implement which expects an array of users name from the database. Generally, with CI..the flow is View form -> Controller -> Database Model(DATA) -> Controller (DATA)-> Another view…but if I have to implement the JQuery/AJAX way then the controller will have to output data so that the AJAX calling function (get) can grab it. Right?
So what should be the flow without affecting the MVC paradigm?
Regards.

MVC is just a design pattern. It tends to make things easier. But its a way of designing your applications, that doesn't mean you have to stick to it.
I work with Codeigniter and use controllers to reply to ajax. In my case the controller is in charge of receiving the request, and sending data back (just as if I was calling a view or template).
Don't overthink it, use what you want,when you want to, the way best fits your needs.

The other option if you really want to stick to mvc is to have a view which you simply use for ajax responses.
You can either have it simply echo the response, or you can have it json_encode() you response if you are always going to be replying using json.

As Nicolás points out, MVC is a design pattern, not law.
However, you should think of AJAX not as a View but as a transport, a medium through which communication between Controller and View or Model and View happens. Thus your actual View is not represented in PHP anymore but by the Browser itself, or rather its JavaScript code that you are running on it. You can abstract away the AJAX on the PHP side using an RPC server like the Zend JSON-RPC Server.
Also note that for Web Applications, the Model-View-Presenter and similar patterns may be more useful as it keeps communication between View and Presenter.

Related

model calls in CodeIgniter

Can we make model calls only from controller?
I make model calls from view also, is it wrong to do so.
Please suggest me.
Thanks.
Well although it's possible, it's really encouraged to do this from the controller and pass the data to the view.
Why? Because heavier calculations such as database request will make the site load funny.
You might first load opening of page, then menu, then the contest takes half a second to pop up due to query being run inside rendering, and not before.
So basic practice:
Let the controller run the heavy stuff, and render the view file simply with given data and avoid rendering too much of it's on.
The Controller serves as an intermediary between the Model, the View,
and any other resources needed to process the HTTP request and
generate a web page.
http://codeigniter.com/user_guide/overview/mvc.html
http://www.tonymarston.net/php-mysql/model-view-controller.html#together
In the MVC structure, the Model is the part that deals with data/database, view are designs/layouts, and controllers are the intermediary between the model and the view.
To answer your question, the Model and the View should never be directly connected in any sense. CodeIgniter may allow you to do so, but it is not what MVC is made for.
You may want to read a little more about MVC structure as a whole

Defining models on server side when using MVVM with Knockout.js

I am planning to use knockout.js and MVVM pattern on the client side for a Single Page application. So Models, ViewModels would be defined on the client side. I am confused about how we have to structure on the server side.
Now, would controllers just return domain model itself ? Would all the mapping from domain model to ViewModel happen only on the client side ?
In my solution, there is wide gap between the Domain model and the ViewModel. So the above approach would result in a lot of data being returned to client side unnecessarily. Though it seems like overkill, I am thinking about repeating ViewModel and InputViewModel definitions (former represents data rendered, latter represents data to be posted back to controller actions) on server side and also having a mapping layer (based on automapper) to map Domain models to ViewModels on the server side. Does this make sense ? Or is there a better approach ?
I would suggest that you work out what data your view models actually need, then have the controllers build up a server-side view model that contains that data and send it to the client in a JSON format.
This way you are not sending unnecessary data over to the client (or back), you are still able to do much of the heavy lifting on the server and the knockout view models can do what they are meant for: presenting the data to be used by the view.
What you described in point 2 is actually the solution I use the most and it makes sense to me:
I use Automapper on the server side to map between Domain models and ViewModels (.Net objects) that are View specific and contain only the data the View needs.
The Controller Action that is responsible for loading the View the first time, will databind the View to the ViewModel, so that the page is initialized quickly without the need to make an Ajax call.
In the View itself I create the knockout viewmodel, assigning any initial values (if needed) by Json encoding the bounded ViewModel (for example using Asp.Net MVC i would do something like
var boundedViewModel = #Html.Raw(Json.Encode(Model));
That is exactly how I would approach this problem. If this were a straight MVC app, you would still be creating viewmodels.
Sometimes for complicated data sets, I can see a use case for using something like Knockback, which takes the rich data model of backbone.js and combines it with knockout.js
http://kmalakoff.github.com/knockback/

Codeigniter Inter Controller Communication

I am new to MVC, CodeIginter. Instead of getting things easy, it needs lot of code to be written for a simple application. These are might be happening becouse I am new. So I have few confusions about this thing. Any kind of help is appreciated.
1) Methods are written in one controller can not be accessed in another controller classes. I have to write a new function for the same functionality.
2) To create website administration panel (back-end) in none mvc panel, we usually create it in a new folder. Is this thing possible in CodeIgniter? If not what about the admin (back-end)??
Let's try to clear some of your doubts about this.
1) Calling a controller's method from another controller is not possible, and it's whtouth meaning by the way.
A controller is supposed to get an action from the URL (which is routed by CI to the right controller for the task) and, based on that, decide which Model and which model's method needs be called to elaborate the data requested.
The model, then, hands back the result of this elaboration to the controller, which , in turns, decides to which view pass this results.
The view, eventually, is structured to get those datas and display them.
SO, as you can see, calling a controllers' method from another controller is nonsense, it would be like going to a page and finding another one instead; if you want to pass to another controller the request...well, there's the redirect for that.
If you find out you have the same functionalities in several moment, think twice:
What is a funcionality? Do you mean somehtin like "display posts" in controller "archive" and "display posts" in controller "news" ? they're hardly the same functionality; they can maybe share views, or models, but that's it.
For functions that doesn't relate to URLs, but involve some further elaboration (which might be wrong to do in Models) and are nonetheless called in a controller, you have library instead. Think at the "form_validation" library, which is called in a controller's method, but has its own peculiar (and encapsulated) functionalies. Ora a "session" library, or an "authentication" library
2) To create an admin panel the easiest thing is: create an "admin" controller (which is accesible then to www.mysite.com/index.php/admin), and put all the administration actions there, in its methods: create_page(), edit_page(), manage_users(), whatever.
In order to avoid people accessing it freely you need to build an authentication system, which, in its simplest and barabone strucutre, might be a check of wheter a session is set or not (maybe a check done at __construct() time).
But you can find nice Auth libraries out there already made, such as Ion Auth or Tank Auth (the 2 most popular to my knowledge)
Hope things are a bit clearer now. See also Interstellar_Coder's comment at this answer if you're interested in the modular HMVC approach.
1) Methods are written in one controller can not be accessed in another controller classes. I have to write a new function for the same functionality.
What's the functionality about? Perhaps you should write a library/helper instead, controller's logic should be limited to request flow or something else but not too complicated. For that, put the functionality in the model, or if more general, in library/helper.
2) To create website administration panel (back-end) in none mvc panel, we usually create it in a new folder. Is this thing possible in CodeIgniter? If not what about the admin (back-end)??
I don't get it, could you elaborate more?

ASP MVC Ajax Controller pattern?

My MVC app tends to have a lot of ajax calls (via JQuery.get()). It's sort of bugging me that my controller is littered with many tiny methods that get called via ajax. It seems to me to be sort of breaking the MVC pattern a bit--the controller is now being more of a data access component then a URI router.
I refactored so that I have my 'true' controller for a page just performing standard routing responses (returing ActionResponse objects). So a call to /home/ will obviously kick up the HomeController class that will respond in the canonical controller fashion by returning a plain-jane View.
I then moved my ajax stuff into a new controller class whose name I'm prefacing with 'Ajax'. So, for example, my page might have three different sections of functionality (say shopping cart or user account). I have an ajax controller for each of these (AjaxCartController, AjaxAccountController). There is really nothing different about moving the ajax call stuff into its own controller class--it's just to keep things cleaner. on client side obviously the JQuery would then use this new controller thusly:
//jquery pseudocode call to specific controller that just handles ajax calls
$.get('AjaxAccount/Details'....
(1) is there a better pattern in MVC for responding to ajax calls?
(2) It seems to me that the MVC model is a bit leaky when it comes to ajax--it's not really 'controlling' stuff. It just happens to be the best and least painful way of handling ajax calls (or am I ignorant)?
In other words, the 'Controller' abstraction doesn't seem to play nice with Ajax (at least from a patterns perspective). Is there something I'm missing?
While you might put Controller on the end of it to make ASP.NET MVC's routing magic work, I tend to do what you've already done--except when I read AjaxCartController I think to myself AjaxCartPresenter (as in the Model-View-Presenter pattern commonly seen in WinForms). That is, this "controller" is not controlling but instead unashamedly tied to the view interface. But, unlike the view, the controller presenter is testable.
When we AJAXify a Web page, we're turning it into something that can react in a fine-grained manner, so fine-grained methods are okay. Fined-grainedness is the point and the whole reason it was invented. We are deliberately walking away from REST for a particular scenario because that particular pattern is not solving the UI requirement at hand, instead choosing an RPC-like model. They are just patterns, one is not going to be better than the other in all situations, even if our technology stack might be pushing us toward one over the other. (Indeed, HTTP itself does better in chunks/pages/entities/representational state transfer documents.)
Mentally, you can treat these pages as if they were forms in a WinForms application; the fact that these methods sit in a "controller" is just an artifact of and concession toward the technology being used. (If it super-duper bothers you, you could roll the AJAX methods into an IHttpHandler and bypass MVC entirely, but why throw away the automatic routing/instantiation/method lookup and make it difficult for yourself? It would be architecturally 'clean' and pure but of dubious benefit.)
... at least, that's how I rationalize it to myself =)
If you have too many fine-grained requests, you might want to have one Controller Action method to service all the calls. You might use a 'switch' in the method to determine the call type and service it accordingly instead of having a zillion tiny methods. You might even use explicit string constants instead of numbers for the switch variable.

MVC: Structuring Feed Output

The framework I'm using on my project follows the MVC Pattern. I"M building JSON feeds and need to structure them in a different way then what the system gives me by default from the ORM. Where should I be handling the task of mangling and shaping my data that I'll serve up, in the model, view or controller?
Right now I'm doing it in my controller, then passing that data to the view. I can see this fitting better under the Model or the View but not sure which one.
If this different structure is only relevant to the view, you should keep it in the view.
If this structure is used in more than one view, make a Helper for it.
Internally your app should standardize on one data format, so models should always return a standardized format. If you were to do something with that data in your controller, you'd need to change the logic for interacting with the data just in that one controller function, which in this case doesn't make much sense. If you later decide to change the format in the model, you'd also need to change code in the controller that interacts with it. Don't create dependencies when there's no advantage to do so.
I'd write a model method to do it if I were you. Having it in the controller will make your controller fat, which is bad, and means you can't call that functionality from other controller actions or anywhere else. Although it could be considered presentation logic, I prefer to keep my views really simple with just conditionals and iterators at most. There may be an argument for having it in a helper, but I'd still stick with the model.

Resources