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.
Related
Quick question for anyone who might have some input.
Normally when I have php/html blocks of code that get used on multiple pages (nav bars, footers, links, etc.) or when I use AJAX to return parts of a page, I assemble that bit of code in a separate file, then include it on the main page as well as in the php insert page to send back with AJAX return data. This works fine.
I've been experimenting with using the same concept except just wrapping my html (which includes php variables) inside of a php function in a separate file, then calling that function where I want it.
If there is a best practice for this, I'm all ears.
There are many ways to handle this, but I think you'll generally find it easier to make a sort of API layer that just returns the data (often serialized to JSON) over AJAX rather than parts of the page.
This separates concerns, allowing you to maintain your API services independently from your pages. It also allows caching of your pages.
To actually handle the updates client-side, there are a number of frameworks to choose from. I've been using Vue.js lately myself. There are also JavaScript-based template engines you can use to render the parts and insert the data into the page.
I am embarking on part of a project now that has me planning on how to load a dynamic table data from a DB. I have uncovered two basic methods.
I believe that I can use url query strings to communicate with the php backend of my phpbb3 forum. And it can load the appropriate data and ship it off to the user in full static page chunks. So I would have something like /stats.php?page=3&orderby=name&dir=desc.
Or I can just send the same empty page to everyone and the browser can dynamically load anything that the user wants using ajax.
Or some combination of the two.
What is best practice? What are the downsides and upsides of both?
It really depends what you're trying to do. For simplicity's sake, I would say that the first option (just load it with the appropriate query string variables in the URL) is better.
Rendering a page using AJAX is pretty much always more complicated. However, it also gives you much more control over the UI if you know what you're doing. From my experience, if you want your page to be more like a "web app" with dynamic things happening everywhere, it is much easier to simply load JSON data from the server via AJAX and to dynamically create views via some sort of templating system. Otherwise you're stuck with loading the DOM with PHP, and then somehow communicating that data to your JavaScript, either by using data-XXX attributes on DOM elements, having PHP output a JSON string at the top of a page and assign it to a JavaScript variable, etc. It could get very complicated and convoluted.
In your case it looks like you're just trying to allow users to view certain data from your forum. Barring any additional requirements, I would recommend going with the first option because it will be much easier. This is simple enough that you don't seem to need to load anything dynamically.
A good rule of thumb is the more complicated and dynamic your UI, the more you should think about moving to a "web app" framework, and just let the server act as a REST server.
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've been tasked to migrate a web application to a more 'modern feeling' AJAX web 2.0 deal. The application as is currently uses PHP to pull data from the database, present the user with forms, and then update the database based on those form submissions. Frames are used to have a persistent main navigation menu, and a content area where the actual
So each php script basically looks for $_POST information; if there is none, it shows the user database data, otherwise it updates data ( provided it is proper data ) and then show the user the result. There are simple get navigations that show subsets.
To migrate this to a AJAX site with a css layout with the content changes happening inside a div, I'm precluded from using POST, because that refreshes the whole page, right? ( I mean I could, but that would be wasteful -- I don't need to regenerate the whole page when only a small part changes.) So basically, the whole task is using Javascript to read the form information, send an XML HTTP Request, and display results? That sounds like a lot of re-writing the existing php funcitonality in javascript, which I would hope to avoid.
Have I understood the task correctly? Are there libraries or frameworks that can help me?
You have two problems here, which are related in some ways, but shouldn't be simply lumped together.
CSS for layout
Only loading part of pages when forms are submitted
I'd work on the separately (while keeping the other in mind as you do so)
First, I suggest you focus on moving to web standards based pages — without introducing Ajax.
It is true that there are some inefficiencies to be had when reloading the whole page, but this approach is simple and relatively easy to debug.
While you do this, consider separating out your display and business logic. The MVC pattern works well for this.
CakePHP is a popular MVC framework that might help.
Once you have a working system, then you can worry about using Ajax. Follow the principles of progressive enhancement.
If you have separated our your display logic from the business logic you should find it relatively simple to reuse your existing code with a different View that provides the data you care about in a JavaScript friendly format (such as JSON).
You can process this to update the parts of the page you care about.
Frameworks that can help you include YUI and jQuery.
I wrote a simple example last year. Lines 51 onwards of the main script pump data into either an HTML template for processing directly by the browser or a JSON module for processing with JS. There isn't a great deal of duplicate effort there since the code for looking at the parameters sent by the user and extracting data from the DB based on it is shared.
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...