Geronimo89.dk

A blog about me, my doings and everything I think deserves attention.

Specialisation report: AJAX+MVC

This is my report for the 3rd semester specialisation at the Nordic Multimedia Academy. My coded twitter clone will be available when I release it for alpha.

Computer programming is tremendous fun. Like music, it is a skill that derives from an unknown blend of innate talent and constant practice. Like drawing, it can be shaped to a variety of ends – commercial, artistic, and pure entertainment. Programmers have a well-deserved reputation for working long hours, but are rarely credited with being driven by creative fevers. Programmers talk about software development on weekends, vacations, and over meals not because they lack imagination, but because their imagination reveals worlds that others cannot see.

from: Larry O’Brien and Bruce Eckel in Thinking in C#

Introduction

As the leading quote, this objective shall for me use principles that naturally further clean code and to split tasks for easy and fast cooperation and maintenance. To code is not that special nowadays as it was before, but to have a high standard and make your software understandable for others is a progressive trend through social coding and sites like github.com, jsfiddle.net or cloud9.com.
Creativity is important for every programmer. To lead this creativity into the right channels, without hindering the workflow, there are architectural guidelines like MVC. It’s short for Model-View-Controller, which I will explain at a later time.
The user is by now used to, that pages are updated on the fly. New messages on facebook or google+ are shown immediately with red tags on the symbol, corresponding to the type of event. On twitter the timeline shows when and how many new tweets have been published since you’ve loaded the page. These features are realized through AJAX (Asynchronous JavaScript and XML). In plain English it means that some of the content of a website is exchanged through JavaScript. This makes the communication between server and client asynchronous and often aids better user interaction.

Model View Controller

Good programmers use their brains, but good guidelines save us having to think out every case.

-Francis Glassborow

The MVC architecture divides a program in three different units, that interact with each other in a specific way. These conventions are in the beginning sometimes seen as a little annoying, but I personally swiftly got used to them and appreciate this way of development. One of the most popular MVC frameworks, Ruby on Rails, runs on twitter.com.

mvc 01 670 Specialisation report: AJAX+MVC

Model

The Model is the part of the program dealing with data storage, reading and writing data to a database. This can be both table based or document based like Google’s BigTable or the CouchDB.

View

A View generates visible output for the user. It’s used to display information and also elements for interaction with the rest of the program.

Controller

As the name already states, the Controller controls the program. A Controller tells the Model which data to get or to write and the Views which to display.

AJAX

Asynchronous JavaScript and XML has majorly influenced the way complex online interfaces are built to aid the user in interacting, achieving goals faster and decreasing loading processes.
Retrieving data when needed, instead of re-generating and re-transferring results with every click, saves both bandwidth and time. Since the development time of a software project usually is significantly smaller than the hours spent using it, it makes perfect sense investing time for development to save time and money on use.
AJAX prevents us from hammering the refresh button, when we’re waiting for an email to arrive and using a webmail interface or show us which users are visiting the websites we are maintaining in realtime (smartly used in piwik).

Used frameworks

The only people who have anything to fear from free software are those whose products are worth even less.

-David Emery

jQuery

It’s the biggest state of the art JavaScript framework today, that is why it is often required by firms and through hundreds of tutorials and a great documentation, very easy to learn.

CodeIgniter

As jQuery, CodeIgniter is quite famous. The framework is developed by EllisLab, but everybody can contribute, fix bugs or add features through github. As it simplifies a lot of everyday tasks for developers and provides a strong and clean structure through the MVC architecture it has built a solid reputation through the past years.

Famous Use Cases

For me, the two most incredible use-cases of AJAX are the operations you either can’t or don’t want to do on the client side, therefore the data is either processed on the server side or just gotten from a database, with checking for authentication and so on.
You could say: AJAX is only for those, who have too much traffic, they only save bandwidth with it. I beg to differ. It can also significantly increase the usability on your website. Waiting is boring and will scare your users away, so you try to give them updates and notifications as quickly and as uncomplicated as possible. The way to do that is AJAX.

Twitter

Twitter has quite elegant use of AJAX all over their page. The most obvious may be the new tweets button. When a new tweet appears in a timeline or in search of a tag, there is a little button on top of the page, that indicates when new tweets have been published.

1newtweet 670 Specialisation report: AJAX+MVC

1newtweet expanded 670 Specialisation report: AJAX+MVC

Why not just put them in there? Because users might not like it. Scrolling output is for running processes on Linux machines, that only geeks handle for monitoring.

What else is handled through AJAX, is user profiles. When you scroll through a list, your own timeline or a tag and click somebodies username, the profile is loaded in the right sidebar. Now, let’s say we have a list of ~100 people and 20 of them have tweeted recently, no profiles are loaded at first. When you click a username, the profile page of the according user appears, showing the recent 3 tweets. By using AJAX you save database (or cache) queries for 60 tweets, statistics for followers, following, amount of tweets and listings for 20. This already sounds like a good deal, right?

Facebook

You may have noticed, that the small red squares show up when you have new messages, notifications or invitations to events on facebook. I’ll not go deeper into this, because this is very similar to twitters, just that the updates are put in a small drop-down box, instead of being pushed into the main content area.

fb notifications 670 Specialisation report: AJAX+MVC

What I think is more interesting is, that when you reach the bottom of a timeline, new content is loaded automatically.

By chopping the informations displayed into smaller chunks and loading them along the way your benefits by using it are:
– less processing time on the server
– less bandwidth consumption
– less rendering time, because less information has to be processed by your browser

MVC

The Model View Controller architecture is used in the aspiring Ruby On Rails framework, which is used by for example Google, Twitter, amazon.com, Yahoo! and BBC. One of the most common PHP frameworks in that category is CodeIgniter which is used to power modelportalen.dk.
If we look at the projects, their services are not the most simple to provide. The characteristics they share are heavy workload, the user expect them to have a high uptime and without errors at any given time. Also neither the maintenance nor the development of the above mentioned is a one-man show.

How does MVC contribute to a collaborative development process?

MVC does more than splitting the jobs into three parts. Current version control systems do more than just to check if a file has been changed. It automatically merges the newest lines together, and only if one line has the same line changed in two different ways, manual work has actually to be done.
With an MVC architecture you would naturally divide your workload into two teams. The web designers / frontend developers would work on the Views, where the developers would stick to the controllers and models. Of course, many others are possible and complex projects require more planning, but it’s already easier and faster, than to hardcode output or write an extensive backend system for placing elements.
Wordpress, in contrast, is a fully featured CMS, so the comparison might sound a little misplaced, but adding functionality to a website that is powered by WordPress usually happens through plugins and modifying the functions.php file within the theme folder. This offers a lot less flexibility to development team, than the above mentioned division.

AJAX login example

To start without combining the MVC and AJAX right away, this is a simple login form test in AJAX.

index.html


		AJAX login form

<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script><script type="text/javascript" src="js/ajaxlogin.js"></script>
</pre>
<form id="login_form" method="post">
User: <input id="username" type="text" />

Password: <input id="password" type="password" />

<input type="submit" value="Login" /></form>
<pre>

The only AJAX specific thing here, is the empty div at the bottom of the page and of course the included script files. The status div will be used to insert the information that the script gives back upon a users login attempt.
ajaxlogin.js

 jQuery(document).ready(function(){
	$('#login_form').submit(function(){
		var unameval = $('#username').val();
		var pwval = $('#password').val();
		$.post('backend.php', { username: unameval, password: pwval },
		function(data){
			$('#status p').html(data);
		});
		return false;
	});
});

This is a straight forward post request, which returns the targeted scripts output and inserts it into the paragraph in the div with the id status. The return false prevents the submit button from actually doing something, because the JavaScript handles it already.

backend.php

<?php
$username = $_POST['username'];
$password = $_POST['password'];

if ($username == 'Zuka' && $password == 'sukinsins'){
	print'Like a boss';
}
else {
	print'Y U FAIL AT LOGIN?';
}

Here we see a contrast to an MVC attempt, as this just is a dummy php file doing the checking, it’s okay to user print and echo, which you would not do in an MVC application, you would load a View.

How does AJAX change the work of a programmer?

Controlling complexity is the essence of computer programming.

-Brian Kernigan

AJAX changes the way of writing a web project and takes it to a little higher level. First of all, you have to make a decision if your project should be usable without JavaScript enabled (web crawlers usually don’t interpret JavaScript). That means that information should be available through alternative hard links, when JavaScript is not used.
Second, you have to keep elements on the same page very modular and easily accessible in the DOM. That sometimes means more encapsulating elements and also writing scripts that only output specific parts of the page, the ones that either are loaded later on or refreshed in page during a visit.
Third, you will write a whole lot JavaScript more than usual and have to take into account that you may need to re-write some parts of the JavaScript upon style changes, to keep the project consistent.
Furthermore you may have to make some changes and process some of the JavaScript through PHP to use variables, constants or other server-side scripting features in your client-side code.
An important thing to remember is to decide if content should be exchanged or refreshed seamlessly or if it should be clarified that something has changed on the site. Loading graphics can be essential to show the uneducated user, that something actually is happening. This can prevent confusion because the communication with the server is visualized. Also error messages upon fail are essential for AJAX powered pages:

fb ajax error Specialisation report: AJAX+MVC

How does MVC change the work of a programmer?

This is more up to the programmer how he/she adapts it. Also how extensively the division into the three parts is undertaken. Basically you CAN make some calculations on output in the View, but you shouldn’t. Also you should not make a Controller output Data directly, around a View, but make it a variable in a View. Data should be ready for display when they leave the Controller.
The really big advantage of working with MVC is the teamwork. The requirements to the individual parts can be very specific, so misunderstandings can be minimized.
When pulling off a project with, for example, a designer and a developer, the designer can send his requirements for the pages in a list and the developer makes sure these data sets are included when the View is loaded, so it can be ordered and styled in the output. This way the two can work both on what they’re best at.

Conclusion

Both using a solid architecture and enhancing user experience through faster interaction is something you have to take care of, to create competitive web projects.
In the paper above I’ve pointed out what is so helpful about the technologies mentioned and why I use them.

Sources

Give me the first comment

Leave a Reply