I am creating an application that will make heavy use of Ajax and performance is required. I've searched the best ways to handle Ajax requests using the Zend Framework, and saw that the most commonly used ways are the Context-switch and/or an Action per Controler to handle Ajax requests. If I were to use the first way I would have to keep a script in the view for each type of format that I could return (JSON, XML, etc.), and I think it's unnecessary, and the second way, I would get an action full of if/elses.
I do not see anyone suggesting the creation of a module only for Ajax, this would be a bad practice? In my opinion this would make things easier, and the whole code for Ajax would be in one place, I would like to know what you think about it before making a decision, and of course, constructive criticism is welcome.
If you have a controller which only needs to handle AJAX, then you can just use the views as usual.
The context switch is meant for cases where an action needs to serve multiple types of contents (JSON, XML, HTML etc.).
If you know that the whole controller will just output JSON, for example, you can create a single view (or no view at all) and call this particular view from all actions in the controller.
Related
I am currently learning jQuery and AJAX and was wondering about best practices for organization of the server-side scripts that handle the AJAX calls. Should I have a handler.php file which then routes the AJAX calls to other functions in different files? Or do you just put everything in one file and use a big switch{}? The system will likely expand in the future and I want to organize it in a way that scales.
A routing file is the way to go, not just for your AJAX requests but for all actions that can be invoked within your system by a web request. You should be placing related actions into a single controller file, and then loading/invoking the correct file/method from your public-facing router.
A good framework, which you absolutely should be using, will do this for you.
What I do is I place the each AJAX call in a function. I name the functions depending on what data I want to retrieve, getUsers(), getComments() etc. Than I call the functions when I need to in JS.
On the PHP side, I use different scripts for each database request. getUsers.php etc...
How do you go about designing/structuring a completely ajaxed MVCish style site? I guess what confuses me the most is that there would only be one view that adapts and changes to the user actions...
I'm looking to build a really simple app, both front end and back end in this style.
Yeah, you'd be building a "front controller" of sorts that would route the views (there would be more than one) to the page for rendering in divs. My company does this with two of its apps and it's lightning fast and a great way to go for a simple app...users love it. Key to the success is a well-formulated layout with well-defined divs to receive the content. As you'll be repeatedly writing and re-writing to them, you have to ensure ahead of time that they are able to handle data of various sizes and amounts as you'll have very few ways to effect layout per page on the overall container....besides after-the-fact hacks (just say no!)
Do as you would with controllers and models and the views (the front-end view code) In some cases our code will use an intermediary page (we call it a mid-model) to generate Jquery data in a JSON string format. It's not quite a model in that case, as it takes action like a model but sometimes returns more than just JSON depending on the needs of the Jquery element.
An interesting offshoot of this system is the use of a program called XAJAX. It's a PHP library that facilitates AJAX called directly to PHP functions, so it eliminates the need to do intermediary JSON generating pages like Jquery uses. For those who understand PHP but struggle with Javascript, this can be an easier solution to grasp. While the documentation hasn't proven very strong, it's a very powerful tool.
I would do all your views as usual (except they would only be HTML fragments that would be inserted into the page) and then have an extra "special" controller and view that loads your views via Ajax. When a link is clicked or something like that the JavaScript makes an Ajax request to the special controller with the view you want to load. The special controller then renders the view and sends it back to be inserted into the page.
Im building a little mvc style framework, with a single point of entry through the index in the public folder. I am now passing all my ajax requests through this, and directing them to the appropriate controllers in the private application directory.
What are the pros and cons of doing it like this?
should I do be doing it like this? or another way?
Initially probably not many cons. As Pickle pointed out you have everything in one area so easy to find.
I would say that functionality should stay in the controller where it belongs. Just because the input and output are AJAX shouldn't matter. In fact, you could have a method in a controller like a show user method that could either output an HTML page OR AJAX data. No reason to put that stuff in a separate AJAX controller when it belongs in the User controller.
Honestly this is all design decisions. It's just my preference to keep things where they belong logically and approach AJAX as an input and output problem and build your methods to handle that in/out.
We rolled our own framework and one thing we build was a router that handles incoming traffic. And ajax calls have a .json at the end. This is then available to the controllers and if a controller supports ajax requests it will output valid JSON data instead of passing the data off to the view and then displaying HTML.
Pros: You don't have to search through a bunch of code to find out where your AJAX request is being handled.
Cons: None I can think of.
The only potential downside would be any "expensive" bootstrapping going on that the AJAX doesn't need which may slow down response times. APC may help or negate this, though, depending on what you are doing, and you could probably tailor the bootstrap process to handle lightweight requests.
FWIW, the normal Drupal method for AJAX funnels everything through the same place as normal pages. This is also done to help provide a fallback when the user doesn't have JS enabled.
I'm building an IMDB.com like website using PHP/jQuery and a MVC approach (no OOP).
I have an index.php base controller to 'rule them all' :), a controllers folder with all the controllers, a models folder and a view folder.
In some pages of the website I have tabbed navigation, when the visitor clicks on one of those tabs to get more information, jQuery gets that data using the $.post or $.get method and shows it on the tab container, obviously without refreshing the page.
The problem is that those pages loaded by ajax are also generated using controllers, models, and views, and the things are getting a bit complicated for someone like me ( = 'no experience'). To dynamically get the data I some times need to include a model twice, include an include in an include in an include, send information multiple times, connect with the database again, and all sort of things like that and I'm sure there is a better and prettier way to do this.
I'm searching for the best approach and common methods for this. I have no experience working with a big project like this. This is a personal project so I have full control and every answer is welcome.
Thanks!!!
You can check the X-Requested-With header that most js frameworks send to see if the request is coming via ajax. Then you can only output certain data and not the "entire page".
Not sure why you need multiple includes like you say, maybe you need to rework your logic.
Post some code and we can be of better help.
"To dynamically get the data I some times need to include a model twice, include an include in an include in an include, send information multiple times, connect with the database again, and all sort of things like that and I'm sure there is a better and prettier way to do this."
I think you need a better 'design' for you MVC application. Multiple includes - i am guessing in the different layers of the MVC framework might be indicators that your design needs more attention.
I'll try and be short:
Other frameworks i.e. handle requests via XMLHTTPRequest by AMONG others, disabling or enabling the VIEW or LAYOUT explicitly - check Zend Framework - (e.g. you need to send a JSON encoded string as a response). These requests are handled just as any other request.
I would suggest you have a look at other popular frameworks. Check the application design and layout, and pay attention on the Routing and Dispatching of Actions. I suggest you follow this path since as you say you lack experience.
good luck with your project.
What's the best way to add dynamic content to a web page after a successfull xml http request. To break down a more concrete example:
User fills in data in input field (e.g. a forum post)
Data is asynchrously updated using the ajax technology
The forum post is instantly displayed for the end user
Sites like Facebook or last.fm (when you post a shout, ie) send the processed markup in a direct object back to the javascript, instead of just the processed data. An example of this written in jQuery would be
$('#activeField').html(callback.data);
Another way to do this is to create the dom elements on the fly with javascript. I find this too clumsy as there's no easy (?) and simple way of doing this today. At the same time, sending the processed markup directly from the server violates our application's design principles (MVC), as having markup in a front controller is not preferred.
What's the "best practices" way of doing this? Thanks!
At the same time, sending the
processed markup directly from the
server vioalates our application's
design principles (MVC), as having
markup in a front controller is not
preferred.
I may be missiing the point, but could you not send markup from the server by rendering it within a view as you would normally, rather than having to have markup in your controller? Assuming your View mechanism has the ability to return rendered HTML rather than outputting it immediately, you could retrieve this and then add it to an array before calling json_encode() and outputting it. You could potentially then use the same view code to render this piece of HTML regardless of whether it is being fetched as part of a full page or via an AJAX call.
I think this question pushes too far on subjective perhaps, but personally I believe the best plan is for the request to return JSON which describes both the content and the mechanism (by which I mean javascript method) for serialising that to HTML if multiple possibilities exist. This saves on bandwidth and (as you've pointed out) preserves your separation of concerns. The last thing I want really is for my front-end guys to have to deal with arbitrary mark-up from the server-side guys. Abstraction is good.
I don't really get why you feel JS generated mark-up is clumsy or difficult. A handful of JS methods which parse and generate standard JSON structures seems lightweight and trivial to me, though I must admit I've always rolled my own here. Almost certainly there's a framework for this out there (anyone?). If not, well I've got this great business idea...