Client-side page rendering, good or bad (PHP + Javascript\AJAX) - php

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.

Related

Best way to load data from MySQL with PHP and Javascript

Looking at other questions, none seem to be specific enough for my case. I am creating a blog-like website and have created a user-authenticated page that allows me to add a title, main content, and image using a form that is sent to a php file that stores the data in the mySQL database. Then, the php redirects me to the index page where I want to load the latest blog post along with all previous posts and put them in a div with styling. I do not think I need AJAX for this. I only need the data to load per each visit, therefore, is the best thing for me to do is to call a javascript function on $(document).ready() that will access the data in the database? If so, how can I implement PHP in my javascript to work with the database and then store the info in javascript variables.
Thanks
You certainly don't need AJAX for this. Just use your index.php page to look up the blog posts in the db and then loop through and echo them out.
You could later incorporate AJAX to call a php page which would provide the blog posts to you. This way you could update the page after it is loaded when new blog posts are created.
Hope that helps.
Clearly you do not seem to have a firm grasp on the role of each language. If you're building something on your own follow the advice of someone who has built ALL of it and can show it off to boot (see my profile, my site contains a blog, forums, private messaging, chat room, CMS, etc all built entirely by myself using no one else's code).
(X)HTML - It's the noun language, an image, a paragraph, a division element used by CSS to style the page, etc.
CSS - The adjective language, describes how the (X)HTML noun language is displayed.
JavaScript - The verb language, event driven; when the user does (onmouseover, onclick, onload, etc) action execute this code (usually a function). AJAX is simply loading content after the page has finished loading. You can worry about the fancy stuff once you have your basics working.
PHP - Server side language, prepares code (mostly XHTML) to be sent to the client's computer.
Database - Where your content is stored.
"$(document).ready() " is not JavaScript, that's jQuery. If you want to learn stay as far away from JavaScript libraries and learn REAL JavaScript otherwise you're going to run in to the nightmares associated with it (crap performance versus native JavaScript, updating libraries changes how you must code to them, etc). Feel free to look at my site's source code as it's all written for XHTML as application/xhtml+xml which means it WILL work in regular HTML though the vast majority of sites do NOT work if you switch them to XHTML. In other words when you code right the first time you'll have much more confidence that it will JUST WORK end of story. People don't care about how you did it but that it works and if it ALWAYS works then they simply can't get any happier with what they have.
If you're building the main blog page you simply need a single SQL query to pull all the content. My blog I programmed to display the last eight latest blog entries though with my pagination it's exactly like a book, the first page (on the left side) starts with the first eight, so if the count isn't divisible by eight you might see six entries on the latest page.
When using SQL you want to CONSTRUCT your query, NEVER stick it inside of a loop! The fewer queries you execute the better your code is and the better your performance. I recommend downloading MySQL Workbench and setting up a MySQL query log and then use Tail for Win32 to view queries in real time to see what your code is doing.
Apache also has logs. You are building this LOCALLY at http:// localhost/ first correct? You should never test something live until you've exhausted testing it locally first. See my base element blog entry about how to best do that...
http://www.jabcreations.com/blog/streamlining-local-and-live-development-with-the-base-element
If you're talking about redirects keep the technical stuff hidden from users and take advantage of $_SESSIONS in PHP. Record what the current page URL is (relative to the base which is different for local/local network/live environments), have a second-URL to fall back to and if that too matches the redirect page then have a safe-URL that is statically defined. If you're constantly falling back to the static URL then check to make sure you haven't goofed up how your other two variables are being updated each page load (such as not updating it if you're on the redirect page obviously).
When you solidify your basic understanding you will want to ask very specific questions as your question is wildly subjective and to most programmers not really worth answering. Make sure you use correct terminology, stick to core languages and not libraries as doing so will help ensure your working code will last that much longer. The stricter your coding practices the better off you'll be. Maximize the sensitivity of your error reporting for HTTP, JavaScript, PHP and SQL errors. Getting PHP is not set errors? What if a hacker is trying to pry error messages from your code? Make sure those variables are set before you even begin to start working with them. Log your errors and fix them fanatically. Don't try to add every feature in the world, concentrate on the critical functionality first and make sure it's incontestably solid before you expand upon it. Do these things and while it may take more time up front you will be rocking harder than the vast majority of people drowning in live environments that are built on not solid code.
gizmovation is right, you don't need AJAX, but to answer the question "how can I implement PHP in my javascript to..."
You're looking to use AJAX. Use jQuery's .ajax to call the PHP page, and when it returns the result, put it into the javascript variables, or directly into the DOM. AJAX example or jQuery example

Prepare data in the backend or manipulate in the frontend?

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.

Web Site code process with server side and client side code. When should the client side code be implemented?

I'm developing a web site, which would make use of PHP, Javascript (JQuery) and use AJAX to connect the two. My question is, how should the coding process go.
I know that Javascript is supposed to be used as an extra kick, and should not be relied upon because it can be turned off. So, should I code the entire site in PHP, and then after all of that is done, add the JQuery code, or should I do both side by side?
If you decide to use AJAX as a core part of the site then you are basically excluding people without javascript which depending on your application can be a legitimate design decision. If you choose to do that then you should check if the user has JavaScript and warn them if they do not.
If you are requiring JavaScript you can develop with it simultaneously with the development of your server side code PHP code. If not, and JavaScript is just a UI enhancement it should be added in later.
Either way validating user input should always also be done on the server side in addition to the client side. All security related code should be only on the server side.
If you are creating a Rich Internet Application than Javascript/Flash/Silverlight will become a requirement of the user in order to use your website. In that case you should perform a check to ensure the user has the correct plugin or javascript enabled. Otherwise display a page which states your site requires it, etc.
If you're just trying to use JavaScript to enhance your site but without it adding a ton of development than the backend would be developed first or if you need to support a large client base then different versions of your site could be made to support JavaScript and non-JavaScript users.
If you want your site to work even if Javascript is disabled, I would develop the site with PHP first and then add your Javascript enhancements. For example, on one site I developed, there is a calendar that lists upcoming events. When the user clicks on that event, a colorbox will appear and the details of that event will be loaded into that colorbox using AJAX. If Javascript is disabled, clicking on the event will just take the user to the event's page.
I think it depends on the approach you take as a programmer.
If you take a top-down approach and start from the user interface and its features, then start from the Javascripts and HTML markup. In the process you can find out how your server API should respond.
If you take a "server capabilities" approach and implement what you can do in the server, then obviously you start implementing that part first. Then you'll continue with the markup and client javascript code, and adapt it to the available APIs that you built. (And probably, in the process, adapt them too).
In both cases, a bit of a design on paper wouldn't hurt.
Of course, as other people have answered, it also greatly depends on how extensive your javascript interface is, how much burden it takes away from PHP, and if you intend to provide an HTML-only interface where the PHP would need to do much of the work.
For instance, let's say you have a table in your code and you want the user to allow to sort it by different columns. This can be done in Javascript, and can be done in PHP, and it can be done in both. It's up to you and your decisions.
If you're planning with jQuery and Ajax in mind then JavaScript off would be almost a completely separate project. However if that is the case, I'd recommend taking the following steps.
Develop the data access and business logic layers.
Build the PHP UI layer w/ full page reloads, etc.
Build an API over the DAL and BL that can be called from JS.
Build the jQuery / Ajax UI from the ground up.
I'm skeptical about the pure server-side UI implementation though, and I'd go about it only if your user base will likely prefer that over the now mainstream JQuery based one.

Client-side or server-side processing?

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).

Sending data from one page to another server. Language agnostic

I'll try to keep this short and simple.
I haven't begun writing the code for this project yet, but I'm trying to work out the pre-coding logistics as of right now.
What I am looking to do, is create a method of sending data from one/any site, to another remote server, which would generate a response for the user requesting the data be sent.
Specifically, a web designer should be able to take a snippet of code I would have available on my website, implement it into their own page(s), and when a user browses their page(s), my service would be available.
A specific example, a web designer with a website (helloworld.com) could implement my code into their page (helloworld.com/index.html). When a user is viewing the page (/index.html), the user hovers the mouse over a text word (lemonade) for a couple seconds, a small dialog box pops up beside it, providing the user with some options specific to the text (example of an option would be "Define 'lemonade' at Dictionary.com") that if selected, would be processed at, and a response would be returned from my remote server (myremoteserver.com)
Obviously, I would want the code that designers would be using to be as lightweight and standalone as possible. Any ideas as to how I could execute this? Resources I should study, and methods I could implement?
Please do not create another one of those services that annoyingly double-underlines words in web site content and then pops up a ugly, slow-to-load ad over the content if I accidentally mouse over the word. Because that sounds like what you're doing.
If you're going to do it anyway, then what the "remote server" will be will probably actually be a bit of client-side JavaScript, in which case JSON is probably your best bet. XML could also work, but even when JavaScript isn't on the other side, I rather like JSON as a serialization technique due to its compactness and readability.
I think you are talking about a hyperlink.
The part that has you confused is the level of interactivity you want on the client site. Whatever sort of neat UI interface you want to wrap around the link will probably be done in javascript and need to be supplied to that site. The core of what you're asking for
text ... that if selected, would be processed at, and a response would be returned from my remote server (myremoteserver.com)
is just a hyperlink.
There's probably more to it than that though. Explain and we'll try to help.
I'll elaborate and furthermore explain that I am not making one of those 'annoying' webservices that turns resourceful information into a clunky billboard. I intend on making a low graphic (16x16 icons at most per menu option) resource linking tool that can be used to connect resources on the local server to other resources, whether local or remote.
This data would be accessed by sending a request to my webserver and returning a response in a popup box (this response would be based on the query of course) The response would be displayed in a brief menu of options, for example Wikipedia entries, links to torrent searches on popular engines, etc.
It won't be inhibitive of selecting, scrolling, clicking predefined hyperlinks, or anything, as you would need to hover the text for a few seconds.
I'm just looking for resources that would be helpful in designing such a service.

Categories