Ok, I'll keep this as concise as possible (I have a tendency to waffle).
I'm making a movie related web app, so I'm making an AJAX request to the backend (PHP) of my app and it is returning me data. At the moment, I return the full JSON to my frontend (jQuery). I then .each() around the data and append the relevant parts + markup to a DIV. Now my question is, do I keep it this way (sending all data back in the request and manipulating it in the frontend) or do I loop around the data in the PHP and just send back markup to the frontend and append it to the DIV without any intervention? Which is better for optimisation? I see both options equal in maintainability.
It's better if you return just the JSON. This will serve as a nice web service and you can even switch to a full RESTful service later on. This will also be less hassle if you end up changing the markup, since you will only need to handle it on the client side. Also, if you have a clean web service going, you can add any amount of consumers (3rd party or not) and these will be able to consume your webservice since you're just returning JSON.
I spent a lot of time thinking about this for an application I was working on and I came to the decision to do generate any markup at the frontend.
The reason I went for this option is because If I ever wanted to create a mobile version of the web app I could do so with no changes to my back-end code. So in the long run it made my application far more manageable and portable to other devices etc.
If all you do at the front end is whack it all into one containing element and the format doesn't change depending on the content - I'd say send markup from the back end.
You can then send that 'chunk' of markup anywhere in your app and you know it'll work without extra front end coding.
Leave an option to return data, incase you want to do something else with it somewhere else.
Rather send markup to the front-end because when you are generating a lot of html from js it will become a nightmare to maintain. Separate business logic from presentation logic (for example using smarty as tpl engine).
That way your php, html and js will stay clean and maintainable as possible.
Related
I am designing the back-end for a web application. I am in a situation where I am unable to collaborate with the front end developer. I also do not like inline HTML\PHP and am not in a position to integrate a template. My solution is that I would keep the front end completely separate from the back-end. The front end would communicate with the back end via AJAX (or jQuery). For example the file upload system would work like this:
<?
//Do stuff
if(!isUserLoggedIn())
die("0-Must be logged in");
//Do more
if(!fileIsTooBigOrNotTheRightType()) {
die("0-Bad files");
}
//Do even more
if(!move_uploaded_file($src,$dst) {
die("0-directory error");
}
echo "1-Success";
?>
The front end developer will simply AJAX the file to upload.php and interpret the response and take the appropriate action on the front end (Show the form, red out some fields, display an error message, redirect to the login form, etc.)
To reduce the number of HTTP queries each page may contain a hidden field with JSON data containing the dynamic elements that will be in place. For example on a private messaging system's inbox page the JSON string may include things such as the number of new messages, who each message is from, and the subject. The front end developer will be able to parse that data and use it any way he likes and is free to create a user friendly interface independent of me.
It is 2012 and I don't think it is wrong to assume the client's have javascript with AJAX support.
TLDR: I am shifting the work of rendering the page (putting elements in their place) to client side javascript. From an efficiency standpoint is this good or bad? It seems like less work the server has to do.
Being both a front and back end developer, my general approach is server-side first, then client side. Make the application work completely and thoroughly without any JavaScript, then move on (or let the front end guy) to the client-side. This ensures that everyone can use your app, even those who don't use JavaScript, such as screen readers and search engines.
What you're referring to is called an API. You make the interface, and then have the frond end developer make API calls to you.
It's possible, though you should be very clear about the specifics of the API (what you can do, and what you can't).
Also make sure you're secure (so that not everyone can access your API).
Other than that, you can do it, sure, no problem.
My suggestion would be to provide a kind of API to the front-end. So, the front-end designer could develop all the HTML, and populate by making javascript calls to your back-end code.
I would then suggest you submit code back to the javascript in JSON format. Javascript handles JSON data structures very well, and the data could then be used to construct the HTML to be injected into the DOM.
I hope I am not too late for the question.
I have done a site based on HTML/Javascript(JQuery) - AJAX - PHP, there is no SEO issue to my site, for example, it's No 3 for Google keywords: free restaurant bookings. Plus, Google has suggested a few ways to work for Javascript, e.g. hidden text.
(My views on the question, please correct me if I am wrong)
Good:
1. More close to MVP model;
2. Clear structure: User interface on front end, PHP/MySQL on server end, AJAX exchange data in between;
3. Easy to change code as of MVP model;
4. Performance: 2 files should be loaded faster than a big file, front-end for data input and validation, server-end for data process
Bad:
1. Javascript maybe disabled (United States: 2.06%, United Kingdom: 1.29%, France: 1.46%, Spain: 1.28%, Brazil: 0.26%) (http://developer.yahoo.com/blogs/ydn/many-users-javascript-disabled-14121.html)
2. Extra coding: JSON/JSONP, AJAX, deal with arrays in PHP and Javascript.
Finally, I suppose that "my general approach is server-side first, then client side." suggested by Madara Uchiha could be more practice, for example, it's what wordpress is using.
Should I have my server return JSON data and then have the JavaScript parse it to create / render HTML directly or should I have my server-side code return HTML directly, which can be directly placed by the JavaScript.
Thoughts?
Render the code server side (e.g. as it is done in Rails' AJAX), then return the view to the client where it will just be placed.
Then profile your code. If it turns out to be too slow, return the JSON and think of a way to render it client-side.
Your priority for this should be to not make the whole thing too copmlicated.
I'm not a fan of returning generated HTML. IMHO I'd return JSON and use something like JQOTE 2 to handle the rendering. Let the clients resources handle that work.
(Side note: JQOTE is an amazing tool!)
I think that if you won't need the data later, e.g. for filtration, on-the-fly search, etc, then you should return HTML.
Premature optimization is the root of all evil. Start with whatever is easier. If it's just too slow, find a way to optimize (perhaps by using an alternative).
If one is not easier than the other to you, go with the server side. I can't imagine a circumstance where a server side scripting language operation would be slower than javascript in a browser.
If all you have to do is render HTML, then it's probably much easier to do it directly with the server (php). Otherwise, you have to convert it to JSON with php first, then convert it back with JS later. That's at least one extra step and extra work for the javascript side.
I'll vote for your first proposed approach.
JSON serialized data size is smaller than (X)HTML one and your first approach saves a lot of CPU cicles, network traffic, memory and speeds-up your client, which ends in a responsive user interface.
Just send data in JSON format and parse it in JavaScript in the client-side so things will be more simpler in the server and rendering things will be delegated to client web browser.
There is no one right answer; it depends on your expectations.
If you want the application to be accessible (ie. processed by a screen reader), picked up by search engine bots or want the UI to be cacheable between requests and users, you will have to use server generated HTML and no dynamic loading. If you use a cache for the generated HTML, you get a lot of mileage without the constant re-rendering. There are more server side tools than client side but that is becoming less of a true statement as JS grows.
OTOH, producing JSON that is rendered by the client using some JS library can really help your server reduce load. You're distributing the work of rendering to the client but that does take control out of your hands. If you have a JS heavy solution and the client can't process JS (screen readers, search engine bots, etc), then the site should degrade gracefully or expect to have some audience that can't view it. That audience might be minuscule for you but it's something to know. As long as you manage the rendering well, (set min size for areas, wait icons, etc) then you can have client side rendering that is as smooth as server side (when comparing visual rendering steps). Producing JSOn also gives you more flexibility as more interfaces are defined or other non-UI clients become important.
It depends on what you are trying to achieve. If you are writing a mobile application you may want to save bandwidth and work with client-side templates (just as an example: John Resig's micro templates). If bandwith is not that important to you I would just use server-side templates to generate the HTML you need.
In my opinion it's all about responsiveness. Your server is ALWAYS going to be able to process data faster than the UA, however the difference between the two may be negligible. If that's the case, then I'd recommend passing JSON to the UA and then use client-side code to do the dirty work. That way, you'll have clear separation of concerns between the server and the client, allowing you to deliver JSON data to different client endpoints in the future without having to modify your server-side code.
However, if there is a significant performance hit with doing the data processing on the client side then it might make more sense to deliver HTML directly to the client. HOWEVER I highly recommend that you still deliver JSON, only to your server-side HTML creation function (rather than the UA) so that you can still deliver JSON data to multiple endpoints without having to alter core code in the future.
I'm designing some UI's for a product and we want to utilize jQuery and PHP. The content to generate is a list of checkboxes (10-100) that a user will be modifying (removing multiple at a time and changing the entries). I thought I'd try something new and ask StackOverflow (read: you) what is preferred: generate the html in the php call and return, or return JSON data that jQuery can than go and generate the html checkboxes using.
I appreciate the feedback! My preferred method so far is to let PHP generate html because it knows more about the data at the time of modification (it's interacting with the database and it could build the html easy enough without having to pass back id's, names, etc in JSON).
Thanks!
[Edit] Bandwidth is not a constraint. This is an internal intranet application. The information needing to be printed to the user will not require dom modification after the fact (outside of checkboxes, but that's built in to the browser...) some good points have been made on the amount of data that's being passed back though:
passing back
Label
vs.
{
"Label": "Unique_ID"
}
is obviously a lot of redundancy.
There's really no right/wrong way to do this. Passing JSON back, and then using client-site processing to turn that into HTML uses less bandwidth, but more local processing power. Passing HTML back, uses more bandwidth and less local processing (these are seriously minor points, only if you're talking extremely popular or frequently changing sites might it even be relevant).
Return Flexibility - HTML
One of the benefits to HTML passing is you can return anything if the request causes an error, or could generate different types of data you just return different HTML. If you're returning JSON, the parsing script has to deal with these alternate structures (ie error handling, and/or multiple structure parsing algorithms).
Local Processing - JSON
If you're localizing, sorting, or framing the data from the user's point of view, it may well be simpler to return JSON and then use client side scripts to interpret. For example when user=2, reporting "You" instead of "Mike" might be a nice personalization touch. You could do this server side, but now the script needs to take that into account, so the same query needs to return different data based on context (again not impossible). You can keep your server code more generic by using client side scripts to perform this.
Local Presenting - JSON
Perhaps a single command collects the data, but there's multiple parts of the page that should be updated with what's returned. With an HTML approach, you either need separate queries, or some sort of delimiter in your return (with escapes!), and a local processing script to decide what goes where... with a JSON approach, the local processing script can update the locations from the same single source as it's retrieved.
You could approach the question both from the aspect of server burden and in terms of client performance.
If your server is having to dynamically generate the HTML output for every user, it will endure a somewhat higher burden than if you delegated the content-generation to client-side JavaScript. Clients have abundant computing power at their disposal, so feel free to have them collectively shoulder the burden rather than having your server do all the work (which could easily add up, depending on how busy your server is).
Likewise, generating the HTML markup on the server results in a significantly larger page download for the client. The markup for a hundred check-boxes could easily add kilobytes to the size of the page, while the data itself--which is all you would send using the JSON approach--is much smaller. Of course, larger page downloads mean longer download times for the client. We as web developers often forget that there are still quite a few people who still have dial-up internet connections.
For these reasons, I would personally opt for sending the data via JSON and doing DOM-modification via JavaScript.
Cheers,
Josh
The answer is: it depends. If you are going to be doing DOM manipulation on the new data, then you pretty much have to append the elements using jQuery. If there is no such manipulation needed, then you can just print it out with php and add the blob.
I think that the latter is much easier and simpler, so if you don't need to do DOM manipulation on the elements, you can just add the html blob from php.
So, I'm new to dynamic web design (my sites have been mostly static with some PHP), and I'm trying to learn the latest technologies in web development (which seems to be AJAX), and I was wondering, if you're transferring a lot of data, is it better to construct the page on the server and "push" it to the user, or is it better to "pull" the data needed and create the HTML around it on the clientside using JavaScript?
More specifically, I'm using CodeIgniter as my PHP framework, and jQuery for JavaScript, and if I wanted to display a table of data to the user (dynamically), would it be better to format the HTML using CodeIgniter (create the tables, add CSS classes to elements, etc..), or would it be better to just serve the raw data using JSON and then build it into a table with jQuery? My intuition says to do it clientside, as it would save bandwidth and the page would probably load quicker with the new JavaScript optimizations all these browsers have now, however, then the site would break for someone not using JavaScript...
Thanks for the help
Congratulations for moving to dynamic sites! I would say the following conditions have to be met for you to do client-side layout (it goes without saying that you should always be doing things like filtering DB queries and controlling access rights server side):
Client browser and connection capabilities are up to snuff for the vast majority of use cases
SEO and mobile/legacy browser degradation are not a big concern (much easier when you synthesize HTML server side)
Even then, doing client-side layout makes testing a lot harder. It also produces rather troublesome synchronization issues. With an AJAX site that loads partials, if part of the page screws up, you might never know, but with regular server-side composition, the entire page is reloaded on every request. It also adds additional challenges to error/timeout handling, session/cookie handling, caching, and navigation (browser back/forward).
Finally, it's a bit harder to produce perma-URLs in case someone wants to share a link with their friends or bookmark a link for themselves. I go over a workaround in my blog post here, or you can have a prominent "permalink" button that displays a dynamically rendered permalink.
Overall, especially when starting out, I would say go with the more kosher, better supported, more tutorialed, traditional approach of putting together the HTML server side. Then dip in some AJAX here and there (maybe start out with form validation or auto-completion), and then move on up.
Good luck!
It is much better to do the heavy lifting on the server side.
In CodeIgniter you create a view, looping through all the rows in the table adding in the classes or whatever else you would need. There is no reason at all to do this in Javascript.
Javascript is a sickly abused language with unfortunate syntax. Why on earth would you want to load a page, and then issue a AJAX call to load up some JSON objects to push into a table is beyond me. There is little reason to do that.
Javascript (and jQuery) is for end user enhancement. Make things slide, flash, disappear! It is not for data processing in even the mildest of loads. The end user experience would be crap because you're relying on their machine to process all the data when you have a server that is infinitely more capable and even designed for this specifically.
It depends on your target market and the goal of your site.
I strongly believe in using the client side where ever you can to offload work from the server. Obviously its important you do it correctly so it remains fast for the end user.
On sites where no-js support is important (public websites, etc), you can have fallbacks to the server. You end up doubling code in these situations but the gains are very beneficial.
For advanced web applications, you can decided if making JS a requirement is worth the trade of losing a (very) few users. For me, if I have some control over the target market, I make it a requirement and move on. It almost never makes sense to spend a ton of time to support a small percentage of potential audience. (Unless the time is spent on accessibility which is different, and VERY important regardless of how many people fit into this group on your site.)
The important thing to remember, is touch the DOM as little as possible to get the job done. This often means building up an HTML string and using a single append action to add it to the page vs looping through a large table and adding one row at a time.
It's better to do as much as possible on the server-side because 1) you don't know if the client will even have JavaScript enabled and 2) you don't know how fast the client-side processing will be. If they have a slow computer and you make them process the entire site, they're going to get pretty ticked off. JavaScript/jQuery is only supposed to be used to enhance your site, not process it.
You got the trade-off correctly. However, keep in mind that you can activate compression in the server side, which will probably make adding repetitive markup to format the table a small bandwidth cost.
Keep also in mind that writing Javascript that works in all browsers (including hand-helds) is more complicated than doing the same server side in PHP. And don't forget that the "new JavaScript optimizations" do not apply to the same extent to browsers of handheld devices.
I do a great deal of AJAX app development and I can tell you this from my experience. a good balance between the two is key.
do the raw data server-side but use javascript to make any modifications that you would need to it. such as paging, column sorting, row striping, etc.
I absolutely love doing everything in AJAX heh.. but there are some short falls to doing it using AJAX, and that's SEO. search engines do not read javascript, so for the sake of your website's page rank, I would say have all data served up server side and then formatted and made look cool client-side.
The reason I love AJAX so much is because it drastically speeds up your APP usage by the user as it only loads the data you need to load where you need to load it, versus load the entire page every time you do something... you can do a whole bunch of stuff, such as hide/show rows/columns (we are talking about table manipulation here because you mentioned a table) and even with these show/hide actions add delete actions where when you click a delete row or button it deletes that row not only visually but in the database all done via AJAX calls to server-side code.
in short.
raw data: server-side sending to the client the raw data in html layout (tables for table structured data, however I do everything else in divs and other flexible html tags, only do tables for column/row style data)
data formatting: client-side which also includes any means of interacting with the data. adding to it, deleting from it, sorting it differently etc. This achieves two things. SEO, and User Experience (UX).
When is it appropriate to use AJAX?
what are the pros and cons of using AJAX?
In response to my last question: some people seemed very adamant that I should only use AJAX if the situation was appropriate:
Should I add AJAX logic to my PHP classes/scripts?
In response to Chad Birch's answer:
Yes, I'm referring to when developing a "standard" site that would employ AJAX for its benefits, and wouldn't be crippled by its application. Using AJAX in a way that would kill search rankings would not be acceptable. So if "keeping the site intact" requires more work, than that would be a "con".
It's a pretty large subject, but you should be using AJAX to enhance the user experience, without making the site totally dependent on it. Remember that search engines and some other visitors won't be able to execute the AJAX, so if you rely on it to load your content, that will not work in your favor.
For example, you might think that it would be nice to have users visit your blog, and then have the page dynamically load the newest article(s) with AJAX once they're already there. However, when Google tries to index your blog, it's just going to get the blank site.
A good search term to find resources related to this subject is "progressive enhancement". There's plenty of good stuff out there, spend some time following the links around. Here's one to start you off:
http://www.alistapart.com/articles/progressiveenhancementwithjavascript/
When you are only updating part of a page or perhaps performing an action that doesn't update the page at all AJAX can be a very good tool. It's much more lightweight than an entire page refresh for something like this. Conversely, if your entire page reloads or you change to a different view, you really should just link (or post) to the new page rather than download it via AJAX and replace the entire contents.
One downside to using AJAX is that it requires javascript to be working OR you to construct your view in such a way that the UI still works without it. This is more complicated than doing it just via normal links/posts.
AJAX is usually used to perform an HTTP request while the page is already loaded (without loading another page).
The most common use is to update part of the view. Note that this does not include refreshing the whole view since you could just navigate to a new page.
Another common use is to submit forms. In all cases, but especially for forms, it is important to have good ways of handling browsers that do not have javascript or where it is disabled.
I think the advantage of using ajax technologies isn't only for creating better user-experiences, the ability to make server calls for only specific data is a huge performance benefit.
Imagine having a huge bandwidth eater site (like stackoverflow), most of the navigation done by users is done through page reloads, and data that is continuously sent over HTTP.
Of course caching and other techniques help this bandwidth over-head problem, but personally I think that sending huge chunks of HTML everytime is really a waste.
Cons are SEO (which doesn't work with highly based ajax sites) and people that have JavaScript disabled.
When your application (or your users) demand a richer user experience than a traditional webpage is able to provide.
Ajax gives you two big things:
Responsiveness - you can update only parts of a web page at a time if need be (saving the time to re-load a page). It also makes it easier to page data that is presented in a table for instance.
User Experience - This goes along with responsiveness. With AJAX you can add animations, cooler popups and special effects to give your web pages a newer, cleaner and cooler look and feel. If no one thinks this is important then look to the iPhone. User Experience draws people into an application and make them want to use it, one of the key steps in ensuring an application's success.
For a good case study, look at this site. AJAX effects like animating your new Answer when posted, popups to tell you you can't do certain things and hints that new answers have been posted since you started your own answer are all part of drawing people into this site and making it successful.
Javascript should always just be an addition to the functionality of your website. You should be able to use and navigate the site without any Javascript involved. You can use Javascript as an addition to existing functionality, for example to avoid full-page reloads. This is an important factor for accessibility. Javascript should never be used as the only possibility to reach or complete a request on your site.
As AJAX makes use of Javascript, the same applies here.
Ajax is primarily used when you want to reload part of a page without reposting all the information to the server.
Cons:
More complicated than doing a normal post (working with different browsers, writing server side code to hadle partial postbacks)
Introduces potential security vulnerabilities (
You are introducing additional code that interacts with the server. This can be a problem on both the client and server.
On the client, you need ways of sending and receiving responses. It's another way of interacting with the browser which means there is another point of entry that has to be guarded. Executing arbritary code, posting data to a non-intended source etc. There are several exploits for Ajax apps that have been plugged over time, but there will always be more.
)
Pros:
It looks flashier to end users
Allows a lot of information to be displayed on the page without having to load all at the same time
Page is more interactive.