Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

March 26 2012

18:11

AJAX User Table Management in CodeIgniter: New on Premium

Learn how to use CodeIgniter and the jQuery library to create a slick, AJAX-utilizing management page for a typical “Users” table, and discover some of the awesome features of jQuery UI.

This Tuts+ Premium exclusive tutorial will guide you through the process of creating a slick, AJAX-utilizing management page for a typical “Users” table in a MySQL database. We will cover a range of topics, in both CodeIgniter and jQuery, including creating and using Models, Controllers and Views, the Form Validation class, and jQuery UI.

preview
preview

Tuts+ Premium

The recently re-launched Tuts+ Premium is a service that provides top-tier training in a variety of creative fields. Whether you prefer books, visual training, or in depth tutorials, we have you covered. While we unfortunately can’t afford to provide the service for free, it’s only $19 a month – less than you’d spend on dinner.

I hope you’ll consider checking it out! In addition to learning a huge variety of new skills, it’s also a fantastic way to say thank you to Nettuts+.


December 02 2011

09:38

Conditional Loading for Responsive Designs

On the eighteenth day of last year’s 24 ways, Paul Hammond wrote a great article called Speed Up Your Site with Delayed Content. He outlined a technique for loading some content — like profile avatars — after the initial page load. This gives you a nice performance boost.

There’s another situation where this kind of delayed loading could be really handy: mobile-first responsive design.

Responsive design combines three techniques:

  • a fluid grid
  • flexible images
  • media queries

At first, responsive design was applied to existing desktop-centric websites to allow the layout to adapt to smaller screen sizes. But more recently it has been combined with another innovative approach called mobile first.

Rather then starting with the big, bloated desktop site and then scaling down for smaller devices, it makes more sense to start with the constraints of the small screen and then scale up for larger viewports. Using this approach, your layout grid, your large images and your media queries are applied on top of the pre-existing small-screen design. It’s taking progressive enhancement to the next level.

One of the great advantages of the mobile-first approach is that it forces you to really focus on the core content of your page. It might be more accurate to think of this as a content-first approach. You don’t have the luxury of sidebars or multiple columns to fill up with content that’s just nice to have rather than essential.

But what happens when you apply your media queries for larger viewports and you do have sidebars and multiple columns? Well, you can load in that nice-to-have content using the same kind of Ajax functionality that Paul described in his article last year. The difference is that you first run a quick test to see if the viewport is wide enough to accommodate the subsidiary content. This is conditional delayed loading.

Consider this situation: I’ve published an article about cats and I’d like to include relevant cat-related news items in the sidebar …but only if there’s enough room on the screen for a sidebar.

I’m going to use Google’s News API to return the search results. This is the ideal time to use delayed loading: I don’t want a third-party service slowing down the rendering of my page so I’m going to fire off the request after my document has loaded.

Here’s an example of the kind of Ajax function that I would write:

  1. var searchNews = function(searchterm) {
  2. var elem = document.createElement('script');
  3. elem.src = 'http://ajax.googleapis.com/ajax/services/search/news?v=1.0&q='+searchterm+'&callback=displayNews';
  4. document.getElementsByTagName('head')[0].appendChild(elem);
  5. };

I’ve provided a callback function called displayNews that takes the JSON result of that Ajax request and adds it an element on the page with the ID newsresults:

  1. var displayNews = function(news) {
  2. var html = '',
  3. items = news.responseData.results,
  4. total = items.length;
  5. if (total>0) {
  6. for (var i=0; i<total; i++) {
  7. var item = items[i];
  8. html+= '<article>';
  9. html+= '<a href="'+item.unescapedUrl+'">';
  10. html+= '<h3>'+item.titleNoFormatting+'</h3>';
  11. html+= '</a>';
  12. html+= '<p>';
  13. html+= item.content;
  14. html+= '</p>';
  15. html+= '</article>';
  16. }
  17. document.getElementById('newsresults').innerHTML = html;
  18. }
  19. };

Now, I can call that function at the bottom of my document:

<script>
    searchNews('cats');
</script>

If I only want to run that search when there’s room for a sidebar, I can wrap it in an if statement:

<script>
if (document.documentElement.clientWidth > 640) {
    searchNews('cats');
}
</script>

If the browser is wider than 640 pixels, that will fire off a search for news stories about cats and put the results into the newsresults element in my markup:

<div id="newsresults">
    <!-- search results go here -->
</div>

This works pretty well but I’m making an assumption that people with small-screen devices wouldn’t be interested in seeing that nice-to-have content. You know what they say about assumptions: they make an ass out of you and umptions. I should really try to give everyone at least the option to get to that extra content:

<div id="newsresults">
    <a href="http://www.google.com/search?q=cats&amp;amp;tbm=nws">Search Google News</a>
</div>

See the result

Visitors with small-screen devices will see that link to the search results; visitors with larger screens will get the search results directly.

I’ve been concentrating on HTML and JavaScript, but this technique has consequences for content strategy and information architecture. Instead of thinking about possible page content in a binary way as either ‘on the page’ or ‘not on the page’, conditional loading introduces a third ‘it’s complicated’ option.

This was just a simple example but I hope it illustrates that conditional loading could become an important part of the content-first responsive design approach.

Tags: ajax
Sponsored post
feedback2020-admin
14:56

September 27 2011

12:14

Searchable Dynamic Content With AJAX Crawling





 



 


Google Search likes simple, easy-to-crawl websites. You like dynamic websites that show off your work and that really pop. But search engines can’t run your JavaScript. That cool AJAX routine that loads your content is hurting your SEO.

Google’s robots parse HTML with ease; they can pull apart Word documents, PDFs and even images from the far corners of your website. But as far as they’re concerned, AJAX content is invisible.

The Problem With AJAX

AJAX has revolutionized the Web, but it has also hidden its content. If you have a Twitter account, try viewing the source of your profile page. There are no tweets there — just code! Almost everything on a Twitter page is built dynamically through JavaScript, and the crawlers can’t see any of it. That’s why Google developed AJAX crawling.

Because Google can’t get dynamic content from HTML, you will need to provide it another way. But there are two big problems: Google won’t run your JavaScript, and it doesn’t trust you.

Google indexes the entire Web, but it doesn’t run JavaScript. Modern websites are little applications that run in the browser, but running those applications as they index is just too slow for Google and everyone else.

The trust problem is trickier. Every website wants to come out first in search results; your website competes with everyone else’s for the top position. Google can’t just give you an API to return your content because some websites use dirty tricks like cloaking to try to rank higher. Search engines can’t trust that you’ll do the right thing.

Google needs a way to let you serve AJAX content to browsers while serving simple HTML to crawlers. In other words, you need the same content in multiple formats.

Two URLs For The Same Content

Let’s start with a simple example. I’m part of an open-source project called Spiffy UI. It’s a Google Web Toolkit (GWT) framework for REST and rapid development. We wanted to show off our framework, so we made SpiffyUI.org using GWT.

GWT is a dynamic framework that puts all of our content in JavaScript. Our index.html file looks like this:

<body>
   <script type="text/javascript" language="javascript"
   src="org.spiffyui.spsample.index.nocache.js"></script>
</body>

Everything is added to the page with JavaScript, and we control our content with hash tags (I’ll explain why a little later). Every time you move to another page in our application, you get a new hash tag. Click on the “CSS” link and you’ll end up here:

http://www.spiffyui.org#css

The URL in the address bar will look like this in most browsers:

http://www.spiffyui.org/?css

We’ve fixed it up with HTML5. I’ll show you how later in this article.

This simple hash works well for our application and makes it bookmarkable, but it isn’t crawlable. Google doesn’t know what a hash tag means or how to get the content from it, but it does provide an alternate method for a website to return content. So, we let Google know that our hash is really JavaScript code instead of just an anchor on the page by adding an exclamation point (a “bang”), like this:

http://www.spiffyui.org#!css

This hash bang is the secret sauce in the whole AJAX crawling scheme. When Google sees these two characters together, it knows that more content is hidden by JavaScript. It gives us a chance to return the full content by making a second request to a special URL:

http://www.spiffyui.org?_escaped_fragment_=css

The new URL has replaced the #! with ?_escaped_fragment_=. Using a URL parameter instead of a hash tag is important, because parameters are sent to the server, whereas hash tags are available only to the browser.

That new URL lets us return the same content in HTML format when Google’s crawler requests it. Confused? Let’s look at how it works, step by step.

Snippets Of HTML

The whole page is rendered in JavaScript. We needed to get that content into HTML so that it is accessible to Google. The first step was to separate SpiffyUI.org into snippets of HTML.

Google still thinks of a website as a set of pages, so we needed to serve our content that way. This was pretty easy with our application, because we have a set of pages, and each one is a separate logical section. The first step was to make the pages bookmarkable.

Bookmarking

Most of the time, JavaScript just changes something within the page: when you click that button or pop up that panel, the URL of the page does not change. That’s fine for simple pages, but when you’re serving content through JavaScript, you want give users unique URLs so that they can bookmark certain areas of your application.

JavaScript applications can change the URL of the current page, so they usually support bookmarking via the addition of hash tags. Hash tags work better than any other URL mechanism because they’re not sent to the server; they’re the only part of the URL that can be changed without having to refresh the page.

The hash tag is essentially a value that makes sense in the context of your application. Choose a tag that is logical for the area of your application that it represents, and add it to the hash like this:

http://www.spiffyui.org#css

When a user accesses this URL again, we use JavaScript to read the hash tag and send the user to the page that contains the CSS.

You can choose anything you want for your hash tag, but try to keep it readable, because users will be looking at it. We give our hashes tags like css, rest and security.

Because you can name the hash tag anything you want, adding the extra bang for Google is easy. Just slide it between the hash and the tag, like this:

http://www.spiffyui.org#!css

You can manage all of your hash tags manually, but most JavaScript history frameworks will do it for you. All of the plug-ins that support HTML4 use hash tags, and many of them have options for making URLs bookmarkable. We use History.js by Ben Lupton. It’s easy to use, it’s open source, and it has excellent support for HTML5 history integration. We’ll talk more about that shortly.

Serving Up Snippets

The hash tag makes an application bookmarkable, and the bang makes it crawlable. Now Google can ask for special escaped-fragment URLs like so:

screenshot

When the crawler accesses our ugly URL, we need to return simple HTML. We can’t handle that in JavaScript because the crawler doesn’t run JavaScript in the crawler. So, it all has to come from the server.

You can implement your server in PHP, Ruby or any other language, as long as it delivers HTML. SpiffyUI.org is a Java application, so we deliver our content with a Java servlet.

The escaped fragment tells us what to serve, and the servlet gives us a place to serve it from. Now we need the actual content.

Getting the content to serve is tricky. Most applications mix the content in with the code; but we don’t want to parse the readable text out of the JavaScript. Luckily, Spiffy UI has an HTML-templating mechanism. The templates are embedded in the JavaScript but also included on the server. When the escaped fragment looks for the ID css, we just have to serve CSSPanel.html.

The template without any styling looks very plain, but Google just needs the content. Users see our page with all of the styles and dynamic features:

screenshot

Google gets only the unstyled version:

screenshot

You can see all of the source code for our SiteMapServlet.java servlet. This servlet is mostly just a look-up table that takes an ID and serves the associated content from somewhere on our server. It’s called SiteMapServlet.java because this class also handles the generation of our site map.

Tying It All Together With A Site Map

Our site map tells the crawler what’s available in our application. Every website should have a site map; AJAX crawling doesn’t work without one.

Site maps are simple XML documents that list the URLs in an application. They can also include data about the priority and update frequency of the app’s pages. Normal entries for site maps look like this:

<url>
   <loc>http://www.spiffyui.org/</loc>
   <lastmod>2011-07-26</lastmod>
   <changefreq>daily</changefreq>
   <priority>1.0</priority>
</url>

Our AJAX-crawlable entries look like this:

<url>
   <loc>http://www.spiffyui.org/#!css</loc>
   <lastmod>2011-07-26</lastmod>
   <changefreq>daily</changefreq>
   <priority>0.8</priority>
</url>

The hash bang tells Google that this is an escaped fragment, and the rest works like any other page. You can mix and match AJAX URLs and regular URLs, and you can use only one site map for everything.

You could write your site map by hand, but there are tools that will save you a lot of time. The key is to format the site map well and submit it to Google Webmaster Tools.

Google Webmaster Tools

Google Webmaster Tools gives you the chance to tell Google about your website. Log in with your Google ID, or create a new account, and then verify your website.

screenshot

Once you’ve verified, you can submit your site map and then Google will start indexing your URLs.

And then you wait. This part is maddening. It took about two weeks for SpiffyUI.org to show up properly in Google Search. I posted to the help forums half a dozen times, thinking it was broken.

There’s no easy way to make sure everything is working, but there are a few tools to help you see what’s going on. The best one is Fetch as Googlebot, which shows you exactly what Google sees when it crawls your website. You can access it in your dashboard in Google Webmaster Tools under “Diagnostics.”

screenshot

Enter a hash bang URL from your website, and click “Fetch.” Google will tell you whether the fetch has succeeded and, if it has, will show you the content it sees.

screenshot

If Fetch as Googlebot works as expected, then you’re returning the escaped URLs correctly. But you should check a few more things:

  • Validate your site map.
  • Manually try the URLs in your site map. Make sure to try the hash-bang and escaped versions.
  • Check the Google result for your website by searching for site:www.yoursite.com.

Making Pretty URLs With HTML5

Twitter leaves the hash bang visible in its URLs, like this:

http://twitter.com/#!/ZackGrossbart

This works well for AJAX crawling, but again, it’s slightly ugly. You can make your URLs prettier by integrating HTML5 history.

Spiffy UI uses HTML5 history integration to turn a hash-bang URL like this…

http://www.spiffyui.org#!css

… into a pretty URL like this:

http://www.spiffyui.org?css

HTML5 history makes it possible to change this URL parameter, because the hash tag is the only part of the URL that you can change in HTML4. If you change anything else, the entire page reloads. HTML5 history changes the entire URL without refreshing the page, and we can make the URL look any way we want.

This nicer URL works in our application, but we still list the hash-bang version on our site map. And when browsers access the hash-bang URL, we change it to the nicer one with a little JavaScript.

Cloaking

Earlier, I mentioned cloaking. It is the practice of trying to boost a website’s ranking in search results by showing one set of pages to Google and another to regular browsers. Google doesn’t like cloaking and may remove offending websites from its search index.

AJAX-crawling applications always show different results to Google than to regular browsers, but it isn’t cloaking if the HTML snippets contain the same content that the user would see in the browser. The real mystery is how Google can tell whether a website is cloaking or not; crawlers can’t compare content programmatically because they don’t run JavaScript. It’s all part of Google’s Googley power.

Regardless of how it’s detected, cloaking is a bad idea. You might not get caught, but if you do, you’ll be removed from the search index.

Hash Bang Is A Little Ugly, But It Works

I’m an engineer, and my first response to this scheme is “Yuck!” It just feels wrong; we’re warping the purpose of URLs and relying on magic strings. But I understand where Google is coming from; the problem is extremely difficult. Search engines need to get useful information from inherently untrustworthy sources: us.

Hash bangs shouldn’t replace every URL on the Web. Some websites have had serious problems with hash-bang URLs because they rely on JavaScript to serve content. Simple pages don’t need hash bangs, but AJAX pages do. The URLs do look a bit ugly, but you can fix that with HTML5.

Further Reading

We’ve covered a lot in this article. Supporting AJAX crawling means that you need to change your client’s code and your server’s code. Here are some links to find out more:

Thanks to Kristen Riley for help with some of the images in this article.

(al)


© Zack Grossbart for Smashing Magazine, 2011.

September 22 2011

18:47

Build Ajax Data Grids with CodeIgniter and jQuery

In this lesson, we will create a CodeIgniter library that allows us to generate data grids automatically for managing any database table. I’ll explain each step required to create this class; so you’ll likely learn some new OOP techniques/concepts in the process!

As a bonus, we’ll proceed to write some jQuery code that will enable a user to update the data grid’s content without having to wait for a page refresh.


Please Note…

This tutorial assumes that you have a modest understanding of the CodeIgniter and jQuery frameworks.

What is a Data Grid?

A datagrid is a table that displays the contents of a database or table along with sorting controls.

A datagrid is a table that displays the contents of a database or table along with sorting controls. In this tutorial, we will be tasked with providing this functionality, but also saving the user from waiting for the page to refresh each time an operation is performed. Thanks to jQuery, this will be a fairly simple task!

What about the users who don’t have Javascript enabled? Don’t worry, we’ll compensate for them as well!


Step 1: Build a Data Grid Generator Class

We want to build a tool that will enable us to create datagrids dynamically for any database table that we have. This means the code is not tied up to any specific table structure, and, thus, is independent on the data itself. All the coder (the developer who uses our class) must know is the name of the table to be transformed into a grid and the primary key for that table. Here is the preface of the class that we will be developing for the most part of this tutorial:

<?php
class Datagrid{
	private $hide_pk_col = true;
	private $hide_cols = array();
	private $tbl_name = '';
	private $pk_col	= '';
	private $headings = array();
	private $tbl_fields = array();
}
?>

The Datagrid Class could well be added to the application/library folder, but we are going to add it as a helper to the CodeIgniter framework. Why? Because loading libraries doesn’t allow us to pass arguments to the class’ constructor, thus loading it as a helper will solve the problem. This point will make more sense for you when we have finished writing the constructor.

The Class’ Constructor Method

public function __construct($tbl_name, $pk_col = 'id'){
	$this->CI =&amp; get_instance();
	$this->CI->load->database();
	$this->tbl_fields = $this->CI->db->list_fields($tbl_name);
	if(!in_array($pk_col,$this->tbl_fields)){
		throw new Exception(&quot;Primary key column '$pk_col' not found in table '$tbl_name'&quot;);
	}
	$this->tbl_name = $tbl_name;
	$this->pk_col = $pk_col;
	$this->CI->load->library('table');

}

We have much going on already; but don’t worry, as I’ll explain everything for you in the next paragraph.

The constructor takes two arguments: the first one being the name of the table in your database that you wish to display as a datagrid to the user; the second param is the name of the column serving as the primary key for that table (more on that later). Inside the constructor’s body, we instantiate the CodeIgniter Object, the Database Object and the HTML Table class/library. All of these will be needed throughout a Datagrid object’s lifetime and are already built into the CI framework. Notice that we also check if the primary key really exists in the given table, and, in case it does not, we throw an exception reporting the error. Now the $this->tbl_fields member variable will be available for later use, so we don’t have to fetch the database again.

“We can use the command, $CI->db->list_fields($tbl_name) to fetch the names of all fields that a table has. However, for better performance, I recommend caching the results.”

Method for Customizing Table Headings

public function setHeadings(array $headings){
	$this->headings = array_merge($this->headings, $headings);
}

This permits you to customize the headings of your data grid table – that is, with it, you can overwrite the original column names for certain table fields. It takes an associative array, like this: regdate => “Registration Date”. Instead of just the technical “Regdate” as the column heading for that type of data, we have a more human-readable title in its place. The code responsible for applying the headings will be revealed shortly.

Method for Ignoring/Hiding Table Fields

public function ignoreFields(array $fields){
	foreach($fields as $f){
		if($f!=$this->pk_col)
			$this->hide_cols[] = $f;
	}
}

ignoreFields receives an array containing the fields to be ignored when fetching data from the database. This is useful when we have tables with lots of fields, but we only want to hide a couple of them. This method is smart enough to track an attempt to ignore the primary key field and then skip that. This is so because the primary key cannot be ignored for technical reasons (you will see why shortly). Still, if you want to hide the primary key column from appearing in the UI, you can use the hidePkCol method:

public function hidePkCol($bool){
	$this->hide_pk_col = (bool)$bool;
}

This method receives a boolean value to indicate if we want to hide the primary key column so it won’t show up in the data grid. Sometimes, it’s an ugly idea to display the pkey data, which is usually a numerical code without any meaning to the user.

Next instance method:

private function _selectFields(){
	foreach($this->tbl_fields as $field){
		if(!in_array($field,$this->hide_cols)){
			$this->CI->db->select($field);
			// hide pk column heading?
			if($field==$this->pk_col &amp;&amp; $this->hide_pk_col) continue;
				$headings[]= isset($this->headings[$field]) ? $this->headings[$field] : ucfirst($field);
		}
	}
	if(!empty($headings)){
		// prepend a checkbox for toggling
		array_unshift($headings,&quot;<input type='checkbox' class='check_toggler'>&quot;);
		$this->CI->table->set_heading($headings);
	}

}

Here we have a helper method; that’s why it has the “private” modifier and is prefixed with an underline character (code convention). It will be used by the generate() method – explained shortly – in order to have the appropriate table fields selected and also the appropriate headings set to the table (generator) object. Notice the following line:

$headings[]= isset($this->headings[$field]) ? $this->headings[$field] : ucfirst($field);

This is where we apply the customized headers or resort to the default ones if none is given. If the pk column is supposed to be hidden from display, then it’s heading will be skipped. Also notice the following line:

array_unshift($headings,&quot;<input type='checkbox' class='dg_check_toggler'>&quot;);

The above command instructs the program to prepend a “Master” checkbox as the first heading of the table. That checkbox is different from other checkboxes in the grid in that it allows a user to check or uncheck all checkboxes in just one go. This toggling functionality will be implemented in a few moments with a simple jQuery code snippet.

Method to Generate/Render the Datagrid

Now comes the thing that does the real work for us:

public function generate(){
	$this->_selectFields();
	$rows = $this->CI->db
			->from($this->tbl_name)
			->get()
			->result_array();
	foreach($rows as &amp;$row){
		$id = $row[$this->pk_col];

		// prepend a checkbox to enable selection of items/rows
		array_unshift($row, &quot;<input class='dg_check_item' type='checkbox' name='dg_item[]' value='$id' />&quot;);

		// hide pk column cell?
		if($this->hide_pk_col){
			unset($row[$this->pk_col]);
		}
	}

	return $this->CI->table->generate($rows);
}

The generate method, as its name suggests, is responsible for generating the data grid itself. You should call this method only after you have configured the object according to your needs. The first thing it does is call the $this->_selectFields() method to perform the actions we explained earlier. Now it has to fetch all rows from the database and then loop through them, adding checkboxes to the beginning of each row:

// prepend a checkbox to enable selection of items/rows
array_unshift($row, &quot;<input class='dg_check_item' type='checkbox' name='dg_item[]' value='$id' />&quot;);

Inside the foreach loop on the generate method, if the $this->hide_pk_col flag is set to true, then we must unset the primary key entry in the $row array so it won’t show up as a column when the $this->CI->table object processes all rows and generates the final html output. At this point, it is okay to remove the primary key, if necessary, because we no longer need that information. A

But what does the user do with the selected/checked rows? To answer this, I have prepared a few more methods. The first one enables us to create “action buttons” without having to know any technical details about how the grid system works internally:

Method for Adding Buttons to a Data Grid Form

public static function createButton($action_name, $label){
	return &quot;<input type='submit' class='$action_name' name='dg_action[$action_name]' value='$label' />&quot;;
}

Simply pass the name of the action as the first argument and a second argument to indicate the label for the generated button. A class attribute is automatically generated for that button so we can play around with it more easily when we are working with it in our JavaScript. But, how do we know if a certain action button has been pressed by the user? The answer can be found in the next method:

public static function getPostAction(){
// get name of submitted action (if any)
	if(isset($_POST['dg_action'])){
		return key($_POST['dg_action']);
	}
}

Yep! Another static method that helps us when we are dealing with forms. If any data grid has been submitted, this method will return the name of the action (or “operation”) associated with that submit event. In addition, another handy tool for processing our datagrid forms is…

public static function getPostItems(){
	if(!empty($_POST['dg_item'])){
		return $_POST['dg_item'];
	}
	return array();
}

… which returns an array containing the selected ids so you can track which rows have been selected on the grid and then perform some action with them. As an example of what can be done with a selection of row ids, I have prepared another method – this one being an instance method, and not a static one, because it makes use of the object’s instance resources in order to do its business:

public function deletePostSelection(){
// remove selected items from the db
	if(!empty($_POST['dg_item']))
		return $this->CI->db
			->from($this->tbl_name)
			->where_in($this->pk_col,$_POST['dg_item'])
			->delete();
}

If at least one checkbox was checked, the deletePostSelection() method will generate and execute an SQL statement like the following (suppose $tbl_name='my_table' and $pk_col='id'):

DELETE FROM my_table WHERE id IN (1,5,7,3,etc...)

…which will effectively remove the selected rows from the persistent layer. There could be more operations you could add to a data grid, but that will depend on the specifics of your project. As a tip, you could extend this class to, say, InboxDatagrid, so, beyond the deletePostSelection method, it could include extra operations, such as moveSelectedMessagesTo($place), etc…

Putting everything together

Now, if you have followed this tutorial step by step, you should have ended up with something similar to the following:

class Datagrid{

	private $hide_pk_col = true;
	private $hide_cols = array();
	private $tbl_name = '';
	private $pk_col	= '';
	private $headings = array();
	private $tbl_fields = array();

	function __construct($tbl_name, $pk_col = 'id'){
		$this->CI =&amp; get_instance();
		$this->CI->load->database();
		$this->tbl_fields = $this->CI->db->list_fields($tbl_name);
		if(!in_array($pk_col,$this->tbl_fields)){
			throw new Exception(&quot;Primary key column '$pk_col' not found in table '$tbl_name'&quot;);
		}
		$this->tbl_name = $tbl_name;
		$this->pk_col = $pk_col;
		$this->CI->load->library('table');

	}

	public function setHeadings(array $headings){
		$this->headings = array_merge($this->headings, $headings);
	}

	public function hidePkCol($bool){
		$this->hide_pk_col = (bool)$bool;
	}

	public function ignoreFields(array $fields){
		foreach($fields as $f){
			if($f!=$this->pk_col)
				$this->hide_cols[] = $f;
		}
	}

	private function _selectFields(){
		foreach($this->tbl_fields as $field){
			if(!in_array($field,$this->hide_cols)){
				$this->CI->db->select($field);
				// hide pk column heading?
				if($field==$this->pk_col &amp;&amp; $this->hide_pk_col) continue;
				$headings[]= isset($this->headings[$field]) ? $this->headings[$field] : ucfirst($field);
			}
		}
		if(!empty($headings)){
			// prepend a checkbox for toggling
			array_unshift($headings,&quot;<input type='checkbox' class='dg_check_toggler'>&quot;);
			$this->CI->table->set_heading($headings);
		}

	}

	public function generate(){
		$this->_selectFields();
		$rows = $this->CI->db
				->from($this->tbl_name)
				->get()
				->result_array();
		foreach($rows as &amp;$row){
			$id = $row[$this->pk_col];

			// prepend a checkbox to enable selection of items
			array_unshift($row, &quot;<input class='dg_check_item' type='checkbox' name='dg_item[]' value='$id' />&quot;);

			// hide pk column?
			if($this->hide_pk_col){
				unset($row[$this->pk_col]);
			}
		}

		return $this->CI->table->generate($rows);
	}

	public static function createButton($action_name, $label){
		return &quot;<input type='submit' class='$action_name' name='dg_action[$action_name]' value='$label' />&quot;;
	}

	public static function getPostAction(){
	// get name of submitted action (if any)
		if(isset($_POST['dg_action'])){
			return key($_POST['dg_action']);
		}
	}

	public static function getPostItems(){
		if(!empty($_POST['dg_item'])){
			return $_POST['dg_item'];
		}
		return array();
	}

	public function deletePostSelection(){
	// remove selected items from the db
		if(!empty($_POST['dg_item']))
			return $this->CI->db
				->from($this->tbl_name)
				->where_in($this->pk_col,$_POST['dg_item'])
				->delete();
	}

}

Notice: Don’t forget to save this file as datagrid_helper.php, and place it in “application/helper/”


Step 2: Testing the Datagrid Helper Class with a CodeIgniter Controller

We’ll now create a simple test controller and load the Datagrid class as a helper in its constructor. But before that, we should define a dummy database table and populate it with some sample data.

Execute the following SQL to create the database and the user table:

CREATE DATABASE `dg_test`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `password` varchar(32) NOT NULL,
  `email` varchar(255) NOT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

Next, let’s add some users to it:

INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES
(1, 'david', '12345', 'david@domain.com'),
(2, 'maria', '464y3y', 'maria@domain.com'),
(3, 'alejandro', 'a42352fawet', 'alejandro@domain.com'),
(4, 'emma', 'f22a3455b2', 'emma@domain.com');

Now, save the following code as “test.php,” and add it to the “application/controllers” folder:

<?php
class Test extends CI_Controller{

	function __construct(){
		parent::__construct();
		$this->load->helper(array('datagrid','url'));
		$this->Datagrid = new Datagrid('users','id');
	}

	function index(){
		$this->load->helper('form');
		$this->load->library('session');

		$this->Datagrid->hidePkCol(true);
		$this->Datagrid->setHeadings(array('email'=>'E-mail'));
		$this->Datagrid->ignoreFields(array('password'));

		if($error = $this->session->flashdata('form_error')){
			echo &quot;<font color=red>$error</font>&quot;;
		}
		echo form_open('test/proc');
		echo $this->Datagrid->generate();
		echo Datagrid::createButton('delete','Delete');
		echo form_close();
	}

	function proc($request_type = ''){
		$this->load->helper('url');
		if($action = Datagrid::getPostAction()){
			$error = &quot;&quot;;
			switch($action){
				case 'delete' :
					if(!$this->Datagrid->deletePostSelection()){
						$error = 'Items could not be deleted';
					}
				break;
			}
			if($request_type!='ajax'){
				$this->load->library('session');
				$this->session->set_flashdata('form_error',$error);
				redirect('test/index');
			} else {
				echo json_encode(array('error' => $error));
			}
		} else {
			die(&quot;Bad Request&quot;);
		}
	}

}
?>

An instance of this class is created and passed as a reference to the $this->Datagrid member. Notice that we will be fetching data from a table called “users” whose primary key is the “id” column; then, on the index method we take the following steps: configure the Datagrid object, render it inside a form with a delete button added to it and see if everything works as expected:

Question: What happens when the form is sent?

Answer: The “Test::proc()” method takes care of processing the form and choosing the right operation to apply against the ids that were selected by the form’s sender. It also takes care of AJAX requests, so it will echo a JSON object back to the client. This AJAX-aware feature will come in handy when jQuery comes into action, which is right now!

“It’s always a smart idea to create web applications which compensates for when JavaScript/AJAX is unavailable. This way, some users will have a richer and faster experience, while those without JavaScript enabled will still be able to use the application normally.”


Step 3: Implementing Ajax (jQuery to the Rescue!)

When the user clicks the button (or any other action button), we would like, perhaps, to prevent the page from reloading and having to generate everything again; this could make the user of our application fall asleep! Circumventing this problem will not be a difficult task if we stick to the jQuery library. Since this is not a “beginners” tutorial, I will not go through all the details related to how to get the library, how to include it on the page, etc. You’re expected to know these steps on your own.

Create a folder, named “js“, add the jQuery library within, and create a view file, named users.php. Open this new file, and add:

<html>
<head>
	<title>Users Management</title>
	<script src=&quot;<?php echo base_url(); ?>js/jquery-1.6.3.min.js&quot;></script>
	<script src=&quot;<?php echo base_url(); ?>js/datagrid.js&quot;></script>
</head>
<body>
<?php
		$this->Datagrid->hidePkCol(true);
		if($error = $this->session->flashdata('form_error')){
			echo &quot;<font color=red>$error</font>&quot;;
		}
		echo form_open('test/proc',array('class'=>'dg_form'));
		echo $this->Datagrid->generate();
		echo Datagrid::createButton('delete','Delete');
		echo form_close();
?>
</body>
</html>

Did you realize that we have moved the code away from Test::index and into the new view script? This means we must change the Test::index() method accordingly:

function index(){
	$this->load->helper('form');
	$this->load->library('session');
	$this->load->view('users');
}

That’s better. If you want to add some styling to the grid, you could use the following CSS (or make a better layout on your own):

	.dg_form table{
		border:1px solid silver;
	}

	.dg_form th{
		background-color:gray;
		font-family:&quot;Courier New&quot;, Courier, mono;
		font-size:12px;
	}

	.dg_form td{
		background-color:gainsboro;
		font-size:12px;
	}

	.dg_form input[type=submit]{
		margin-top:2px;
	}

Now, please, create a “datagrid.js” file, put it on the “js” directory, and start with this code:

$(function(){
	// cool stuff here...
})

Inside this closure, we will write code that will be tasked with controlling certain submit events once the page has completely loaded. The first thing we need to do is track when a user clicks a submit button on the data grid form, and then send that data to be processed on the server.

 	$('.dg_form :submit').click(function(e){
		e.preventDefault();
		var $form = $(this).parents('form');
		var action_name = $(this).attr('class').replace(&quot;dg_action_&quot;,&quot;&quot;);
		var action_control = $('<input type=&quot;hidden&quot; name=&quot;dg_action['+action_name+']&quot; value=1 />');

		$form.append(action_control);

		var post_data = $form.serialize();
		action_control.remove();

		var script = $form.attr('action')+'/ajax';
		$.post(script, post_data, function(resp){
			if(resp.error){
				alert(resp.error);
			} else {
				switch(action_name){
					case 'delete' :
						// remove deleted rows from the grid
						$form.find('.dg_check_item:checked').parents('tr').remove();
					break;
					case 'anotherAction' :
						// do something else...
					break;
				}
			}
		}, 'json')
	})

Alternatively, we could have started with something like: $('.dg_form').submit(function(e){...}). However, since I want to track which button has been pressed and extract the name of the chosen action based on it, I prefer binding an event handler to the submit button itself and then go my way up the hierarchy of nodes to find the form that the pressed button belongs to:

// finds the form
var $form = $(this).parents('form');
// extracts the name of the action
var action_name = $(this).attr('class').replace(&quot;dg_action_&quot;,&quot;&quot;);

Next, we add a hidden input element inside the form element to indicate which action is being sent:

// create the hidden input
var action_control = $('<input type=&quot;hidden&quot; name=&quot;dg_action['+action_name+']&quot; value=1 />');
// add to the form
$form.append(action_control);

This is necessary because function doesn’t consider the submit button to be a valid form entry. So we must have that hack in place when serializing the form data.

action_control.remove();

“Don’t forget: the function ignores the submit button, dismissing it as just another piece of markup junk!”

Sending Form Data to the Server

Next, we proceed to get the action attribute from the form element and append the string “/ajax” to that url, so the method will know that this is, in fact, an AJAX request. Following that, we use the jQuery.post function to send the data to be processed by the appropriate controller, server-side, and then intercept the response event with a registered callback/closure:

...
	var script = $form.attr('action')+'/ajax';
	$.post(script, post_data, function(resp){
		if(resp.error){
			alert(resp.error);
		} else {
			switch(action_name){
				case 'delete' :
					// remove deleted rows from the grid
					$form.find('.dg_check_item:checked').parents('tr').remove();
				break;
				case 'anotherAction' :
					// do something else...
				break;
			}
		}
	},'json')

Notice that we are asking the response to be encoded as “json” since we are passing that string as the fourth argument of the $.post function. The contents of the callback dealing with the server response should be rather simple to grasp; it determines if there is an error, and, if so, alerts it. Otherwise, it will indicate that the action was successfully processed (in this case, if it is a “” action, we remove the rows related to the ids that were selected by the user).


Step 4: Check All or Nothing!

The only thing that is missing now is the toggle functionality that I promised earlier. We must register a callback function for when the “Master” checkbox – which has a class attribute set to “dg_check_toggler” – is clicked. Add the following code snippet after the previous one:

	$('.dg_check_toggler').click(function(){
		var checkboxes = $(this).parents('table').find('.dg_check_item');
		if($(this).is(':checked')){
			checkboxes.attr('checked','true');
		} else {
			checkboxes.removeAttr('checked');
		}
	})

When the “toggler” checkbox is clicked, if it goes to a “checked” state, then all rows from the pertaining data grid will be checked simultaneously; otherwise everything will be unchecked.


Final Thoughts

We haven’t reached the tip of the iceberg when it comes to data grids for more complex content management systems. Other features which might prove to be useful are:

  • Sorting the data grid by column names
  • Pagination links for browsing the data grid
  • Edit/Modify links for updating a single row’s data
  • Search mechanism to filter results

Thanks for reading. If you’d like a follow-up tutorial, let me know in the comments!


September 08 2011

15:10

How to Upload Files with CodeIgniter and AJAX

Uploading files asnychronously can be a pain at the best of times, but when coupled with CodeIgniter, it can be a particularly frustrating experience. I finally found a way that not only works consistently, but keeps to the MVC pattern. Read on to find out how!


Preface

In this tutorial, we’ll be using the PHP framework CodeIgniter, the JavaScript framework jQuery, and the script AjaxFileUpload.

It’s assumed you have a working knowledge of CodeIgniter and jQuery, but no prior knowledge of AjaxFileUpload is necessary. It is also assumed that you already have an install of CodeIgniter already set up.

For the sake of brevity, the loading in of certain libraries/models/helpers has been omitted. These can be found in the source code supplied, and is pretty standard stuff.

You’ll also need a database, and a table, called files. The SQL to create said table is:

CREATE TABLE `files` (
  `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `filename` varchar(255) NOT NULL,
  `title` varchar(100) NOT NULL
);

By the end of the tutorial, your file structure should look similar to this (omitting unchaged folders/files):

public_html/
– application/
—- controllers/
—— upload.php
—- models/
—— files_model.php
—- views/
—— upload.php
—— files.php
– css/
—- style.css
– files/
– js/
—- AjaxFileUpload.js
—- site.js


Step 1 - Creating the Form

Set up the Controller

First, we need to create our upload form. Create a new Controller, called upload, and in the index method, render the view upload.

Your controller should look like this:

class Upload extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('files_model');
		$this->load->database();
		$this->load->helper('url');
	}

	public function index()
	{
		$this->load->view('upload');
	}
}

We are also loading in the files model, so we can use it in our methods. A better alternative may be to autoload it in your actual project.

Create the Form

Create your view, upload.php. This view will contain our upload form.

<!doctype html>
<html>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
	<script src="<?php echo base_url()?>js/site.js"></script>
	<script src="<?php echo base_url()?>js/ajaxfileupload.js"></script>
	<link href="<?php echo base_url()?>css/style.css" rel="stylesheet" />
</head>
<body>
	<h1>Upload File</h1>
	<form method="post" action="" id="upload_file">
		<label for="title">Title</label>
		<input type="text" name="title" id="title" value="" />

		<label for="userfile">File</label>
		<input type="file" name="userfile" id="userfile" size="20" />

		<input type="submit" name="submit" id="submit" />
	</form>
	<h2>Files</h2>
	<div id="files"></div>
</body>
</html>

Don’t forget to place ajaxfileupload.js in js/.

As you can see, we are loading in our scripts at the top; jQuery, AjaxFileUpload, and our own js file. This will house our custom JavaScript.

Then, we are simply creating a standard HTML form. The empty #files div is where our list of uploaded files will be.

Some Simple CSS

Just so it doesn’t look quite so bad, lets add some basic CSS to our file style.css in css/.

h1, h2 { font-family: Arial, sans-serif; font-size: 25px; }
h2 { font-size: 20px; }

label { font-family: Verdana, sans-serif; font-size: 12px; display: block; }
input { padding: 3px 5px; width: 250px; margin: 0 0 10px; }
input[type="file"] { padding-left: 0; }
input[type="submit"] { width: auto; }

#files { font-family: Verdana, sans-serif; font-size: 11px; }
#files strong { font-size: 13px; }
#files a { float: right; margin: 0 0 5px 10px; }
#files ul {	list-style: none; padding-left: 0; }
#files li { width: 280px; font-size: 12px; padding: 5px 0; border-bottom: 1px solid #CCC; }

Step 2 - The Javascript

Create and open site.js in js/. Place the following code:

$(function() {
	$('#upload_file').submit(function(e) {
		e.preventDefault();
		$.ajaxFileUpload({
			url 			:'./upload/upload_file/',
			secureuri		:false,
			fileElementId	:'userfile',
			dataType		: 'json',
			data			: {
				'title'				: $('#title').val()
			},
			success	: function (data, status)
			{
				if(data.status != 'error')
				{
					$('#files').html('<p>Reloading files...</p>');
					refresh_files();
					$('#title').val('');
				}
				alert(data.msg);
			}
		});
		return false;
	});
});

The JavaScript hijacks the form submit and AjaxFileUpload takes over. In the background, it creates an iframe and submits the data via that.

We’re passing across the title value in the data parameter of the AJAX call. If you had any more fields in the form, you’d pass them here.

We then check our return (which will be in JSON). If no error occured, we refresh the file list (see below), clear the title field. Regardless, we alert the response message.


Step 3 - Uploading the File

The Controller

Now on to uploading the file. The URL we are uploading to is /upload/upload_file/, so create a new method in the upload controller, and place the following code in it.

public function upload_file()
{
	$status = "";
	$msg = "";
	$file_element_name = 'userfile';

	if (empty($_POST['title']))
	{
		$status = "error";
		$msg = "Please enter a title";
	}

	if ($status != "error")
	{
		$config['upload_path'] = './files/';
		$config['allowed_types'] = 'gif|jpg|png|doc|txt';
		$config['max_size']	= 1024 * 8;
		$config['encrypt_name'] = TRUE;

		$this->load->library('upload', $config);

		if (!$this->upload->do_upload($file_element_name))
		{
			$status = 'error';
			$msg = $this->upload->display_errors('', '');
		}
		else
		{
			$data = $this->upload->data();
			$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
			if($file_id)
			{
				$status = "success";
				$msg = "File successfully uploaded";
			}
			else
			{
				unlink($data['full_path']);
				$status = "error";
				$msg = "Something went wrong when saving the file, please try again.";
			}
		}
		@unlink($_FILES[$file_element_name]);
	}
	echo json_encode(array('status' => $status, 'msg' => $msg));
}

This code loads in the CodeIgniter upload library with a custom config. For a full reference of it, check out the CodeIgniter docs.

We do a simple check to determine if the title is empty or not. If it isn’t, we load in the CodeIgniter upload library. This library handles a lot of our file validation for us.

Next, we attempt to upload the file. if successful, we save the title and the filename (passed in via the returned data array).

Remember to delete the temp file off the server, and echo out the JSON so we know what happened.

The Model

In keeping with the MVC pattern, our DB interaction will be handled by a model.

Create files_model.php, and add the following code:

class Files_Model extends CI_Model {

	public function insert_file($filename, $title)
	{
		$data = array(
			'filename'		=> $filename,
			'title'			=> $title
		);
		$this->db->insert('files', $data);
		return $this->db->insert_id();
	}

}

Files Folder

We should also create the folder our files will be uploaded to. Create new file in your web root called files, making sure it is writable by the server.


Step 4 - The File List

Upon a successful upload, we need to refresh the files list to display the change.

The JavaScript

Open site.js and add the following code to the bottom of the file, below everything else.

function refresh_files()
{
	$.get('./upload/files/')
	.success(function (data){
		$('#files').html(data);
	});
}

This simply calls a url and inserts the returned data into a div with an id of files.

We need to call this function on the page load to initially show the file list. Add this in the document ready function at the top of the file:

refresh_files();

The Controller

The URL we are calling to get the file list is /upload/files/, so create a new method called files, and place in the following code:

public function files()
{
	$files = $this->files_model->get_files();
	$this->load->view('files', array('files' => $files));
}

Quite a small method, we use our model to load in the currently saved files and pass it off to a view.

The Model

Our model handles the retrieval of the file list. Open up files_model.php, and add in the get_files() function.

public function get_files()
{
	return $this->db->select()
			->from('files')
			->get()
			->result();
}

Quite simple really: select all the files stored in the database.

The View

We need to create a view to display the list of files. Create a new file, called files.php, and paste in the following code:

<?php
if (isset($files) && count($files))
{
	?>
		<ul>
			<?php
			foreach ($files as $file)
			{
				?>
				<li class="image_wrap">
					<a href="#" class="delete_file_link" data-file_id="<?php echo $file->id?>">Delete</a>
					<strong><?php echo $file->title?></strong>
					<br />
					<?php echo $file->filename?>
				</li>
				<?php
			}
			?>
		</ul>
	</form>
	<?php
}
else
{
	?>
	<p>No Files Uploaded</p>
	<?php
}
?>

This loops through the files and displays the title and filename of each. We also display a delete link, which include a data attribute of the file ID.


Deleting the File

To round off the tutorial, we’ll add in the functionality to delete the file, also using AJAX.

The JavaScript

Add the following in the document ready function:

$('.delete_file_link').live('click', function(e) {
	e.preventDefault();
	if (confirm('Are you sure you want to delete this file?'))
	{
		var link = $(this);
		$.ajax({
			url			: './upload/delete_file/' + link.data('file_id'),
			dataType	: 'json',
			success		: function (data)
			{
				files = $(#files);
				if (data.status === "success")
				{
					link.parents('li').fadeOut('fast', function() {
						$(this).remove();
						if (files.find('li').length == 0)
						{
							files.html('<p>No Files Uploaded</p>');
						}
					});
				}
				else
				{
					alert(data.msg);
				}
			}
		});
	}
});

It’s always a good idea to get a user confirmation when deleting information.

When a delete link is clicked, we display a confirm box asking if the user is sure. If they are, we make a call to /upload/delete_file, and if successful, we fade it from the list.

The Controller

Like above, the url we are calling is /upload/delete_file/, so create the method delete_file, and add the following code:

public function delete_file($file_id)
{
	if ($this->files_model->delete_file($file_id))
	{
		$status = 'success';
		$msg = 'File successfully deleted';
	}
	else
	{
		$status = 'error';
		$msg = 'Something went wrong when deleteing the file, please try again';
	}
	echo json_encode(array('status' => $status, 'msg' => $msg));
}

Again, we let the model do the heavy lifting, echoing out the output.

The Model

We’re now at the final piece of the puzzle: our last two methods.

public function delete_file($file_id)
{
	$file = $this->get_file($file_id);
	if (!$this->db->where('id', $file_id)->delete('files'))
	{
		return FALSE;
	}
	unlink('./files/' . $file->filename);
	return TRUE;
}

public function get_file($file_id)
{
	return $this->db->select()
			->from('files')
			->where('id', $file_id)
			->get()
			->row();
}

Because we only pass the ID, we need to get the filename, so we create a new method to load the file. Once loaded, we delete the record and remove the file from the server.

That’s it, tutorial complete! If you run it, you should be able to upload a file, see it appear, and then delete it; all without leaving the page.


Final Thoughts

Obviously, the views can do with some prettying up, but this tutorial should have given you enough to be able to integrate this into your site.

There are a few shortcomings to this method, however:

  • You can only upload one file at a time, but this can rectified easily by using a service like Uploadify.
  • There is no progress bar built into the script.
  • We could reduce the SQL calls by updating the files div upon file upload, instead of fully replacing them.

Thanks for reading!


September 02 2011

00:19

Extensive Collection Of Useful jQuery Plugins For Working With Tables

jQuery plugins are quite in these days in the field of web designing and are extensively used because of their aesthetically appealing results. Through jQuery tables plugins, you can attain the maximum results in terms of functionality and flexibility. The level of flexibility and functionality that jQuery provide cannot be met with classic HTML tables.

Here we are presenting a collection of exceptional and highly functional jQuery tables plugins that let you create user-friendly tables easily and efficiently. Enjoy!

Table Pagination

( Demo | Download )
This jquery plugin is used to create a pagination element under a table element. You can customize your pagination needs through various settings.

Tablesorter

( Demo | Download )
tablesorter is a jQuery plugin for turning a standard HTML table with THEAD and TBODY tags into a sortable table without page refreshes. tablesorter can successfully parse and sort many types of data including linked data in a cell.

Animated Sortable Data Table jQuery plugin – jTPS

( Demo | Download )
jTPS is a datatable jQuery plugin that offers pagination, animated scrolling through pages and intelligent natural sorting capability. The development version is currently 15KB.

Flexigrid

( Demo | Download )
Lightweight but rich data grid with resizable columns and a scrolling data to match the headers, plus an ability to connect to an XML based data source using Ajax to load the content.

Animated table sort

( Demo | Download )
This plugin allows you to animatedly sort a table based on a column’s td’s, or on the content/value of a child/descendant element within those td’s. The various td’s fly to their new homes, giving a nice effect. It also supports sorting on REGEXP matches. You can also control whether row relationships are maintained, whether it sorts on ascii or numeric and ascending or descending.

HeatColor, a jQuery plugin

( Demo | Download )
HeatColor is a plugin that allows you to assign colors to elements, based on a value derived from that element. The derived value is compared to a range of values, either determined automatically or passed in, and the element is assigned a “heat” color based on its derived value’s position within the range.

Collapser

( Demo | Download )
Jquery collapser is a multi purpose collapser plugin made for expanding and collapsing elements. Can create a accordion, list collapser using this plugin.

jExpand

( Demo | Download )
jExpand is ultra lightweight jQuery plugin that will make your tables expandable. Typical for line of business applications, this feature can help you organize tables better. This way, tables can hold more information such as images, lists, diagrams and other elements.

Tree Table

( Demo | Download )
The treeTable plugin allows you to display a tree in a table, i.e. a directory structure or a nested list. Each branch in this tree can be collapsed and expanded, just like in a file explorer in most modern operating systems.

Table Drag and Drop

( Demo | Download )
This TableDnD plugin allows the user to reorder rows within a table, for example if they represent an ordered list. Individual rows can be marked as non-draggable and/or non-droppable. Rows can have as many cells as necessary and the cells can contain form elements.

jQuery charToTable plugin

( Demo | Download )
With this useful plugin you can convert characters to tables using jQuery.

Add Table Rows Count

( Demo | Download )
With jQuery rowCount plugin you can automatically add table row count column to your tables.

uiTableFilter

( Demo | Download )
uiTableFilter is a jquery plugin for filtering table rows.

Ingrid

( Demo | Download )
Ingrid is an unobtrusive jQuery component that adds datagrid behaviors (column resizing, paging, sorting, row and column styling, and more) to your tables.

JQTreeTable

( Demo | Download )
Take a plain html table, wrap the rows you want collapsing/expanding in a tbody with an id of treetable, map each row to it’s parent row, set some options, and let jQTreeTable take it from there.

PicNet Table Filter

( Demo | Download )
This jQuery plugin adds real time Google-like column filtering capabilities to a regular Html table. This is an open source project released under The MIT License (MIT).

TableEditor

( Demo | Download )
TableEditor provides flexible in place editing of HTML tables. User defined handler functions can easily be dropped in to, for example, update the data source via an AJAX request.

jQuery ColumnManager plugin

( Demo | Download )
A jQuery-plugin to toggle the visibility of table columns (collapsing and expanding them) and to save the state until the next visit. It’s supporting tables with colspans and rowspans, too!

CSV2 Table

( Demo | Download )
This plugin loads a CVS file (e.g. created using Excel) and creates a table with the contents in that CVS file.

JSquared

( Demo | Download )
JSquared Enables ability to add/remove HTML table columns and rows.

jQuery.kiketable.rowsizable

( Demo | Download )
This plugin, applied to n-tables of an HTML page, provides the behaviour of resizing rows by clicking over a “image handler”.

Graphtable

( Demo | Download )
graphTable provides the ability to graph the data in a simple HTML table using flot.

Grider

( Demo | Download )
Grider is a plugin for jQuery that makes your life easier when you need to edit or create a table that handles a list of items. It helps you to do calculations in a very simple way, it supports the following features.

jQuery floating table header plugin

( Demo | Download )
A jQuery plugin that makes the header of a table floating if the original header isn’t visible due to scrolling. The plugin will automatically choose the thead tag as the header for a table. If thead isn’t found it will search for rows marked with the class ‘floating’. The behavior can be changed by the settings forceClass and markingClass.

LiveFilter

( Demo | Download )
LiveFilter is a very lightweight jQuery plugin that will filter either an ordered or unordered list and display only the results that match the supplied string.

TinySort

( Demo | Download )
TinySort will sort any nodetype by it’s text- or attribute value, or by that of one of it’s children.

Using jQuery To Manipulate and Filter Data

( Demo | Download )
When a webpage is designed to display large tables of data, a great amount of consideration should be dedicated to allowing the user to sort through the data in a structured manner. In this tutorial, author will go over four techniques: hover effects, zebra rows, filtering, and sorting.

Creating a “Filterable” Portfolio with jQuery

( Demo | Download )
If you have worked in your field for a while, there is a pretty good chance that you have a rather extensive portfolio. To make it a little easier to navigate, you will probably be tempted to break them into different categories. In this tutorial, you can learn how to make “filtering by category” a little more interesting with just a little bit of jQuery.

List Reorder

( Demo | Download )
List Reorder is a jQuery plugin that allows you to reorder any simple ordered or unordered list. List Reorder is easy to use and does not require any additional markup. Its look and feel is completely customizable using a set of CSS classes.

DragTable

( Demo | Download )
Maybe you want to sort the columns ascending/descending by clicking into the table-head. No problem! Use a handle to drag the rows.

FireScope Grid

( Demo | Download )
FireScope Grid is an open source (GNU Public License, v2) jQuery component that adds datagrid behaviors to your HTML tables, regardless of the server-side technology being used. Included in the plugin is a navigation bar that is automatically appended at the beginning or end of a table that enables users to page through results, filter results by any column or sorted on the fly without need to refresh the entire page.

Fixed Header Tables

( Demo | Download )
FixedHeaderTable in its simplest form displays a fixed header for any valid table mark-up. This is an active jQuery plugin project so expect new features and improvements to be released.

JGridEditor

( Demo | Download )
This jQuery plugin allow you to add on-the-flight cell editing functionality in your table You may configure it to perform AJAX queries and returning changed content or error messages.

pfSelect – click drag select for huge datasets

( Demo | Download )
This lightweight select plugin allows you to select elements easily by click-drag select, shift select or ctrl select within a huge dataset and without any speed decrease. It adds a mouseover event to each specified element (by default elements with class “selectable”) and doesn’t calculate any marquee rectangle as the Jquery UI plugin does. Therefore it has no performance issues with hundreds of elements. Use this plugin if you have tons of elements and you need fluid interactivity.

Sortable Tables

( Demo | Download )
jQuery Accessible RIA, a collection of strictly WAI WCAG 2.0 and WAI ARIA conform web applications based on the popular Java-Script framework jQuery (using the UI Widget Factory).

KeyTable

( Demo | Download )
KeyTable is a Javascript library which provides keyboard navigation and event binding for any HTML table. With KeyTable Excel style table navigation can be employed to provide features such as editing of a table without requiring a mouse. As a further bonus, KeyTable integrates seamlessly with DataTables.

Zentable

( Demo | Download )
Zentable is a plug-in for the jQuery Javascript library. It allows to show and manipulate tabulated data on a web page but with functionalities typically expected from native applications, as scrolling with the mouse wheel, resizing column widths or using keys to move through the data. It can be used with or without AJAX, but is using AJAX where this plug-in really shines.

jQuery Week Calendar

( Demo | Download )
The jquery-week-calendar plugin provides a simple and flexible way of including a weekly calendar in your application. It is built on top of jquery and jquery ui and is inspired by other online weekly calendars such as google calendar.

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

August 15 2011

15:57

45 jQuery Plugins And Tutorials To Enhance Your Forms

Creating awesome and appealing forms for your website has now become easy, thanks to jQuery plugins. Here we are sharing with you a collection of some extremely useful plugins and tutorials to help you create beautiful and awesome web forms.

Web forms are the crucial element for any website as website visitors use such forms to interact with the webmaster. Therefore, keeping them neat and functional while maintaining their aesthetic appeal is important. Here is the complete list. Enjoy!

Boxy –Facebook-like dialog/overlay ( Demo | Download )
Boxy is a flexible, Facebook-style dialog box for jQuery with support for dragging and size tweening.

Screenshot

A jQuery Inline Form Validation ( Demo | Download )
When it comes to form validation, it’s hard to have a versatile solution that works with every form. Figuring out how to display errors is not a simple task. When an error needs to be displayed, the script creates a div and positions it in the top right corner of the input. This way you don’t have to worry about your HTML form structure. The rounded corner and shadow are done with CSS3 and degrade well in non compliant browsers.

Screenshot

ToChecklist plugin ( Demo | Download )
The toChecklist plugin for jQuery will give you the functionality of a SELECT box without the need to ctrl+click items to select them.

Screenshot

A Fancy Contact Form ( Demo | Download )
Providing a simple and reliable means of feedback from site visitors is a crucial part of any web presence. The most simple and common feedback channel are contact forms. In this tutorial we are going to make an AJAX contact form which leverages modern web development techniques.

Screenshot

Select Multiple Form Fields ( Demo | Download )
asmSelect is a jQuery plugin that answers some of these issues. A progressive enhancement is applied to the select multiple that makes it much easier to use. This enhancement automatically hides the original select multiple, and instead presents a regular select showing the available options, and an HTML list showing the already-selected options.

Screenshot

Creating a Digg Style Sign Up Form ( Demo | Download )
In this tutorial we are going to simulate their signup form, with unique features such as their dynamic tooltips that give you a hint on each field that is to be filled. The same approach will be adopted for displaying validation messages.

Screenshot

jQuery Show Password Plugin ( Demo | Download )
This plugin works by adding a text field that takes the value of what is typed into the password field. Then, when the link is clicked the password field is hidden and the text field is shown.

Screenshot

Create an AJAX/jQuery/PHP Contact Form ( Demo | Download )
This tutorial uses XHTML, CSS, jQuery and a little PHP to make a pop-up/modal contact form that validates whatever is entered into the form and then uses AJAX to send the form without refreshing the page.

Screenshot

LightForm ( Demo | Download )
LightForm is a free Ajax/PHP contact form. It combines FormCheck2 for fields validation and NiceForms to style text fields and textareas.

Screenshot

MeioMask ( Demo | Download )
With meioMask plugin you can create and apply maskstot text input fields.

Screenshot

LiveValidation ( Demo | Download )
LiveValidation is a small open source javascript library for making client-side validation quick, easy, and powerful. It comprises of two main parts. Firstly, it provides developers with a rich set of core validation methods, which can also be used outside the context of forms.

Screenshot

WordPress plugins for contact forms ( Demo | Download )
There are lots of WordPress plugins for contact forms, but wouldn’t it be nice to have more control over the markup? In this tutorial, Trevor is going to show how to use a custom page template to create a contact form in WordPress without a plugin.

Screenshot

How to Enhance Forms Using jQuery UI ( Demo | Download )
jQuery makes creating UI so much easier without compromising speed and quality. In this tutorial we are going to enhance form using jQuery UI, so let’s get started

Screenshot

Submit A Form Without Page Refresh using jQuery ( Demo | Download )
Submit a contact form that sends an email, without page refresh using jQuery, This tutorial will help you creating a form that can be submitted without page refreshing, using JQuery.

Screenshot

Timepickr ( Demo | Download )
jquery.timepickr was created in a attempt to make the process of inputing time in a form as easy and natural as possible.

Screenshot

Password Strength Indicator and Generator ( Demo | Download )
In the example about you will see two password boxes and with them you have a generate password link and an icon showing you the strength of your password.

Screenshot

JQByte StickyForms ( Demo | Download )
StickyForms is a jQuery plugin that automatically saves all form fields into cookies, and then autofills those values on any form that shares element IDs across your site.

Screenshot

File Style jQuery ( Demo | Download )
Browsers do not let you style file inputs. File Style plugin fixes this problem. It enables you to use image as browse button. You can also style filename field as normal textfield using css. It is written using JavaScript and jQuery.

Screenshot

Autocomplete ( Demo | Download )
By giving an autocompleted field focus or entering something into it, the plugin starts searching for matching entries and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

Screenshot

Emblematiq Niceforms ( Demo | Download )
You basically know a web form when you see one as they always look the same and they’ve kept this look over the years. Try as hard as you might but web forms can only change their appearance so much. Some may argue that this is a good usability feature, and I tend to agree, but there comes a time when you just need to style web forms so that they look different. How do you do that? Niceforms comes to the rescue!

Screenshot

A BETTER FORM – SPAM-LESS ROBOT-LESS FORMS ( Demo | Download )
A Better Form is a jQuery plugin I designed to help eliminate spam comments, spam emails and other automated form submissions.

Screenshot

Progress Bar ( Demo | Download )
It’s a very simple widget with a small API that exposes a limited number of properties and methods, but it can still be highly effective and is great for providing visual feedback to visitors on the percentage of a process is left before it is complete.

Screenshot

jQuery AlphaNumeric ( Demo | Download )
jQuery AlphaNumeric is a javascript control plugin that allows you to limit what characters a user can enter on textboxes or textareas.

Screenshot

Build An Incredible Login Form With jQuery ( Demo | Download )
In this tutorial, we’ll create a sliding panel, that slides in to reveal more content, using JQuery to animate the height of the panel. In this case, we will be creating a hypothetical login for the new tutsplus area that’s coming soon.

Screenshot

prettyCheckboxes ( Demo | Download )
This script is for people who wants to have a consistent look for checkboxes across browser or those who simply want them to look better. By using this script you wont loose any of the regular inputs usability.

Screenshot

Improved Current Field Highlighting in Forms ( Demo | Download )
In this tutorial CSS expert Chris Coyier will tell you how to improve your form usuability and enhance them visually.

Screenshot

jQuery Ajax delete ( Demo | Download )
Removing contents with Ajax is a useful tool to have in any web designers kit. Using a few lines of jQuery we can remove a div and simultaneously remove a record from the database with Ajax. In the download and demo you’ll see a small red cross to the right of each comment. Clicking the cross will remove the comment div with a slide up animation which will remove the div. click the image below to check out the demo.

Screenshot

jQuery Auto Complete ( Demo | Download )
Auto-complete takes input from the user, and tries to form a list of words that match the users input. The function attaches itself to the input field selected, and also creates the UL drop down from within so all you need is have the styles for it ready.

Screenshot

Date Picker ( Demo | Download )
Date Picker component with a lot of options and easy to fit in your web application.

Screenshot

Plugin for Password Masking ( Demo | Download )
This plugin gives users the option to see the chracters of the password the are entering, for usability purposes.

Screenshot

jQuery Form Plugin ( Demo | Download )
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process.

Screenshot

Input Fields with Images ( Demo | Download )
With this plugin you can add icons or images inside of input fields to add some flair to your forms.

Screenshot

Elastic ( Demo | Download )
Elastic makes your textareas grow and shrink to fit it’s content. It was inspired by the auto growing textareas on Facebook. The major difference between Elastic and it’s competitors is it’s weight.

Screenshot

jQuery Checkbox ( Demo | Download )
This plugin allows you to style your forms checkboxes or radio buttons.

Screenshot

iPhone Style Checkboxes ( Demo | Download )
With this plugin you can enhance standard HTML checkboxes and gives them an iPhone-like styling.

Screenshot

jQuery Autosave ( Demo | Download )
Autosave is designed to save the progress of forms by saving the fields to cookies so you won’t lose anything should anything go wrong. The plug-in saves the form fields at certain intervals (the default is every 10 seconds) and whenever you leave the page.

Screenshot

AutoTab ( Demo | Download )
Autotab provides smart auto-tabbing and filtering on text fields in a form. Simply put: once you have typed the maximum number of characters in a text field, you will automatically have focus on the next defined text field. Target text fields are defined, as well as a defined previous text field.

Screenshot

Magicpreview ( Demo | Download )
Magicpreview automatically updates selected elements on a page based on form fields. Perfect for previewing forms.

Screenshot

Using form labels as text field values ( Demo | Download )
When designing you sometimes have limited space to put and display all of the form elements. Recently that happened to me and when I was trying to squeeze in a simple newsletter form to a 120px wide area (plus a limited height). I realized that some of the elements will have to go. The obvious solution was to get rid of the labels and put only the form text fields. How will the users know what are the text fields for? I will use value attributes and write the explanation in there, something like “Input your email here”. Problem solved? Not quite. Why? Because I am a web standards freak :)

Screenshot

Checking username availability with ajax using jQuery ( Demo | Download )
The time when username availability is checked after the page is normaly processed is long way behind us. Google has it, Yahoo has it and many many more sites have it, ajax username availability checker. So in this tutorial we will make an ajax username availability checker powered with jQuery.

Screenshot

jQuery Highlight plugin ( Demo | Download )
Highlight increases usability by highlighting elements as you interact with the page. Its primary use is for forms, but it can also be used for tables, lists, or any element you specify. It can also be used to toggle elements on and off, for example, table rows.

Screenshot

A Fancy AJAX Contact Form ( Demo | Download )
Ajax Fancy Captcha is a jQuery plugin that helps you protect your web pages from bots and spammers. We are introducing you to a new, intuitive way of completing “verify humanity” tasks. In order to do that you are asked to drag and drop specified item into a circle.

Screenshot

ASM Select ( Demo | Download )
A progressive enhancement to select multiple form elements. It provides a simpler alternative with lots of advantages.

Screenshot

BABYSTEPS ( Demo | Download )
BabySteps (A ‘What About Bob?’ reference) is a simple and easily configurable tool for turning long forms into broken out steps without going from page to page.

Screenshot

BS FORM ACCELERATOR ( Demo | Download )
BS Form Accelerator will be able to use Enter or Space buttons in your forms replacing the buttons such as Tab for changing focus in fields just with assigning an ID to the form.

Screenshot

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

July 26 2011

01:24

Uploading Files with AJAX

I can’t seem to reach the end of the fun stuff you can do with emerging web technologies. Today, I’m going to show you how to do something that—until the last while—has been almost unprecedented: uploading files via AJAX.

Oh, sure, there have been hacks; but if you’re like me, and feel dirty every type you type iframe, you’re going to like this a lot. Join me after the jump!


Why don’t we get the bad news over with?

This doesn’t work in every browser. However, with some progressive enhancement (or whatever the current buzzword is), we’ll have an upload page that will work right back to IE6 (albeit without the AJAXy bits).

Our AJAX upload will work as long as FormData is available; otherwise, the user will get a normal upload.

There are three main components to our project.

  • The multiple attribute on the file input element.
  • The FileReader object from the new File API.
  • The FormData object from XMLHttpRequest2.

We use the multiple attribute to allow the user to select multiple files for upload (multiple file upload will work normally even if FormData isn’t available). As you’ll see, FileReader allows us to show the user thumbnails of the files they’re uploading (we’ll be expecting images).

None of our three features work in IE9, so all IE users will get a normal upload experience (though I understand support for `FileReader` is available in IE10 Dev Preview 2). FileReader doesn’t work in the latest version of Safari (5.1), so they won’t get the thumbnails, but they’ll get the AJAX upload and the confirmation message. Finally, Opera 10.50 has FileReader support but not FormData support, so they’ll get thumbnails, but normal uploads.

With that out of the way, let’s get coding!


Step 1: The Markup and Styling

Let’s start with some basic markup and styling. Of course, this isn’t the main part of this tutorial, I won’t treat you like a newbie.

The HTML

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>HTML5 File API</title>
	<link rel="stylesheet" href="style.css" />
</head>
<body>
	<div id="main">
		<h1>Upload Your Images</h1>
		<form method="post" enctype="multipart/form-data"  action="upload.php">
			<input type="file" name="images" id="images" multiple />
			<button type="submit" id="btn">Upload Files!</button>
		</form>

		<div id="response"></div>
		<ul id="image-list">

		</ul>
	</div>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
	<script src="upload.js"></script>
</body>
</html>

Pretty basic, eh? We’ve got a form that posts to upload.php, which we’ll look at in a second, and a single input element, of type file. Notice that it has the boolean multiple attribute, which allows the user to select multiple files at once.

That’s really all there is to see here. Let’s move on.

The CSS

body {
	font: 14px/1.5 helvetica-neue, helvetica, arial, san-serif;
	padding:10px;
}

h1 {
	margin-top:0;
}

#main {
	width: 300px;
	margin:auto;
	background: #ececec;
	padding: 20px;
	border: 1px solid #ccc;
}

#image-list {
	list-style:none;
	margin:0;
	padding:0;
}
#image-list li {
	background: #fff;
	border: 1px solid #ccc;
	text-align:center;
	padding:20px;
	margin-bottom:19px;
}
#image-list li img {
	width: 258px;
	vertical-align: middle;
	border:1px solid #474747;
}

Absolutely no shockers here.


Step 2: The PHP

We need to be able to handle the file uploads on the back end as well, so let’s cover that next.

upload.php

<?php

foreach ($_FILES["images"]["error"] as $key => $error) {
	if ($error == UPLOAD_ERR_OK) {
		$name = $_FILES["images"]["name"][$key];
		move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
	}
}

echo "<h2>Successfully Uploaded Images</h2>";

Bear in mind that these were the first lines of PHP I’d written in easily a year (I’m a Ruby guy). You should probably be doing a bit more for security; however, we’re simply making sure that there are no upload errors. If that’s the case, we use the built-in move_uploaded_file to move it to an uploads folder. Don’t forget to make sure that the folder is writable.

So, right now, we should have a working upload form. You choose an image (multiple, if you want to and your browser lets you), click the “Upload Files!” button, and you get the message “Successfully Uploaded Images.

Here’s what our mini-project looks like so far:

The styled form

But, come on, it’s 2011: we want more than that. You’ll notice that we’ve linked up jQuery and an upload.js file. Let’s crack that open now.


Step 3: The JavaScript

Let’s not waste time: here we go!

(function () {
	var input = document.getElementById("images"),
	    formdata = false;

	if (window.FormData) {
		formdata = new FormData();
		document.getElementById("btn").style.display = "none";
	}

}();

Here’s what we start with. We create two variables: input is our file input element; formdata will be used to send the images to the server if the browser supports that. We initialize it to false and then check to see if the browser supports FormData; If it does, we create a new FormData object. Also, if we can submit the images with AJAX, we don’t need the “Upload Images!” button, so we can hide it. Why don’t we need it? Well, we’re going to auto-magically upload the images immediately after the user selects them.

The rest of the JavaScript will go inside your anonymous self-invoking function. We next create a little helper function that will show the images once the browser has them:

function showUploadedItem (source) {
	var list = document.getElementById("image-list"),
	    li   = document.createElement("li"),
	    img  = document.createElement("img");
  	img.src = source;
  	li.appendChild(img);
	list.appendChild(li);
}

The function takes one parameter: the image source (we’ll see how we get that soon). Then, we simply find the list in our markup and create a list item and image. We set the image source to the source we received, put the image in the list item, and put the list item in the list. Voila!

Next, we have to actually take the images, display them, and upload them. As we’ve said, we’ll do this when the onchange event is fired on the input element.

if (input.addEventListener) {
	input.addEventListener("change", function (evt) {
		var i = 0, len = this.files.length, img, reader, file;

		document.getElementById("response").innerHTML = "Uploading . . ."

		for ( ; i < len; i++ ) {
			file = this.files[i];

			if (!!file.type.match(/image.*/)) {

			}
		}

	}, false);
}

We don’t have to worry about IE’s proprietary event model, because IE9+ supports the standard addEventListener function.

There’s more, but let’s start with this. First off, we don’t have to worry about IE’s proprietary event model, because IE9+ supports the standard addEventListener function (and IE9 and down don’t support our new features).

So, what do we want to do when the user has selected files? First, we create a few variables. The only important one right now is len = this.files.length. The files that the user has selected will be accessible from the object this.files. Right now, we’re only concerned with the length property, so we can loop over the files …

… which is exactly what we’re doing next. Inside our loop, we set the current file to file for ease of access. Next thing we do is confirm that the file is an image. We can do this by comparing the type property with a regular expression. We’re looking for a type that starts with “image” and is followed by anything. (The double-bang in front just converts the result to a boolean.)

So, what do we do if we have an image on our hands?

if ( window.FileReader ) {
	reader = new FileReader();
	reader.onloadend = function (e) {
		showUploadedItem(e.target.result);
	};
	reader.readAsDataURL(file);
}
if (formdata) {
	formdata.append("images[]", file);
}

We check to see if the browser supports creating FileReader objects. If it does, we’ll create one.

Here’s how we use a FileReader object: We’re going to pass our file object to the reader.readAsDataURL method. This creates a data url for the uploaded image. It doesn’t work the way you might expect, though. The data url isn’t passed back from the function. Instead, the data url will be part of an event object.

With that in mind, we’ll need to register a function on the reader.onloadend event. This function takes an event object, by which we get the data url: it’s at e.target.result (yes, e.target is the reader object, but I had issues when using reader in place of e.target inside this function). We’re just going to pass this data url to our showUploadedItem function (which we wrote above).

Next, we check for the formdata object. Remember, if the browser supports FormData, formdata will be a FormData object; otherwise, it will be false. So, if we have a FormData object, we’re going to call the append method. The purpose of a FormData object is to hold values that you’re submitting via a form; so, the append method simply takes a key and a value. In our case, our key is images[]; by adding the square-brackets to the end, we make sure each time we append another value, we’re actually appending it to that array, instead of overwriting the image property.

We’re almost done. In our for loop, we’ve displayed each of the images for the user and added them to the formdata object. Now, we just need to upload the images. Outside the for loop, here’s the last piece of our puzzle:

if (formdata) {
	$.ajax({
		url: "upload.php",
		type: "POST",
		data: formdata,
		processData: false,
		contentType: false,
		success: function (res) {
			document.getElementById("response").innerHTML = res;
		}
	});
}

Again, we have to make sure we have FormData support; if we don’t, the “Upload Files!” button will be visible, and that’s how the user will upload the photos. However, if we have FormData support, we’ll take care of uploading via AJAX. We’re using jQuery to handle all the oddities of AJAX across browsers.

You’re probably familiar with jQuery’s $.ajax method: you pass it an options object. The url, type, and success properties should be obvious. The data property is our formdata object. Notice those processData and contentType properties. According to jQuery’s documentation, processData is true by default, and will process and transform the data into a query string. We don’t want to do that, so we set this to false. We’re also setting contentType to false to make sure that data gets to the server as we expect it to.

And that’s it. Now, when the user loads the page, they see this:

Tutorial Image

And after they select the images, they’ll see this:

Tutorial Image

And the images have been uploaded:

Tutorial Image

That’s a Wrap!

Uploading files via AJAX is pretty cool, and it’s great that these new technologies support that without the need for lengthy hacks. If you’ve got any questions about what we’ve done here, hit those comments! Thank you so much for reading!


April 08 2011

17:08

Best Practices for test revisited

With Google and their apps like Search, Docs or GMail only a very small time is actually spent in the initial page load, writes Andreas Grabner in a recent blog post. Of course, much time is spent in JavaScript, XHR Calls and DOM Manipulations triggered by user actions. Grabner writes:

It is very important to speed up Page Load Time – don’t get me wrong. It is the initial perceived performance by a user who interacts with your site. But it is not all we need to focus on. Most of the time in modern web applications is spent in JavaScript, DOM Manipulations, XHR Calls and Rendering that happen after the initial page load. Automatic verification against Best Practices won’t work here anymore because we have to analyze individual user actions that do totally different things. The way this will work is to analyze the individual user actions, track performance metrics and automate regression detection based on these measured values.

February 24 2011

18:57

Fun with jQuery Templating and AJAX


In this tutorial, we’ll take a look at how jQuery’s beta templating system can be put to excellent use in order to completely decouple our HTML from our scripts. We’ll also take a quick look at jQuery 1.5′s completely revamped AJAX module.


What’s Templating?

Templating is a newish (it’s still in beta, so it’s likely to change slightly as it matures and migrates into core, but it’s been around for the best part of a year), hugely powerful jQuery feature that allows us to specify a template to use when building DOM structures via script, something that I’m sure we all do on an almost daily basis.

It’s always been incredibly easy when using jQuery to do something like this:

$("#someElement").children().each(function() {
	$(this).wrap($("<div></div>"));
});

Templating allows us to remove these string-based snippets of HTML from our behaviour.

This will simply wrap each child element of #someElement in a new <div> element. There’s nothing particularly wrong with doing this; it’s perfectly valid and works well in countless situations. But, that’s HTML there in our script — content mixed up with behaviour. In the simple example above it’s not a huge issue, but real-world scripts could contain many more snippets of HTML, especially when building DOM structures with data obtained via an AJAX request. The whole thing can quickly become a mess.

Templating allows us to remove these string-based snippets of HTML from our behaviour layer, and put them back firmly where they belong in the content layer. While we’re doing that, we can also check out one of the brand new, super-cool AJAX features of jQuery 1.5 – deferred objects.


Getting Started

In this example, we’ll build a Twitter widget that will not only load some of our recent tweets, but also list some friends, followers and suggestions. I chose Twitter for this example because it outputs JSON in the format we require; it’s easy and fun.

So let’s get started; the widget itself will be built from the following underlying mark-up:

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>jQuery, AJAX and Templating</title>
        <link rel="stylesheet" href="tweetbox.css">
        <!--[if lte IE 8]>
			<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->
	</head>
		<body>
		<aside id="tweetbox">
			<div id="user">
            	<h2><a href="http://twitter.com/danwellman" title="Visit Dan Wellman on Twitter">Dan Wellman</a></h2>
	            <a href="http://twitter.com/danwellman" title="Dan Wellman"><img src="img/me.png" alt="Dan Wellman"></a>
				<p>Husband, father, front-end developer and author. Writes for Nettuts and Packt Publishing. Works for <a href="http://twitter/.com/designhaus" title="Design Haus">@designhaus</a> | jQuery fanatic :D </p>
			</div>
			<ul id="tools">
				<li><a href="#tweets" title="Recent Tweets" class="on">Tweets</a></li>
				<li><a href="#friends" title="Recent Friends">Friends</a></li>
				<li><a href="#follows" title="Recent Followers">Followers</a></li>
			</ul>
			<div id="feed">
				<div id="tweets">
					<noscript>This widget has super-awesome features which require the use of JavaScript. Please enable it for a better internet experience</noscript>
				</div>
				<div id="friends"></div>
				<div id="follows"></div>
			</div>
		</aside>
		<script src="jquery.js"></script>
		<script src="jquery.tmpl.min.js"></script>
		<script src="tweetbox.js"></script>
	</body>
</html>
Unstyled

We’re using HTML5 and have included the simplified DOCTYPE and meta charset element. We link to a custom style sheet, which we’ll create in a moment, and in order to support current versions of IE8 and lower, we use a conditional comment to link to the Google-hosted html5shiv file.

Using aside

This widget would probably go into a sidebar, and be distinct from the actual content of the page it is featured on, but related to the site as a whole. With that in mind, I feel an <aside> is an appropriate outer container in this case. We give it an id for easy selecting and styling.

Continuing on with our markup, we have some details about the Twitter user whose tweets are listed, including the name in a <h2>, an image and the bio in a standard <p>. Feel free to change these to your own details when reconstructing the example. We could get all of these items from the JSON call that we’ll make when we request the data, however, if there is a slight delay in the request at page load, the visitor could be left staring at a bunch of empty boxes, so hard-coding this info into the widget is again, appropriate. If we were making a plugin for other developers to consume, we certainly couldn’t do this, but when adding this to our own site, or a specific client’s site, this is a feasible approach.

Next, we have the tabs that will be used to switch between the tweets, friends and followers. These are built from a simple collection of <ul>, <li> and <a> elements. The friends tab will be displayed by default, so the link for this tab has the class on attached to it. In a larger project, we could of course use jQuery UI tabs, but I didn’t want the tutorial to lose focus, and it’s no bother to add this functionality ourselves manually.

Notice that we’re also using a plugin – this is the tmpl (templating) plugin, which gives us the ability to use jQuery templates.

Finally, we have the elements that will hold each stream of data; we have an outer container with an id of feed, and three containers for the tweets, friends and followers respectively, which also have id attributes for easy selecting. We also include a <noscript> element for visitors that may have scripting disabled (if any actually exist anymore), which is within the default tab content area. Notice that we’re also using a plugin – this is the tmpl (templating) plugin, which gives us the ability to use jQuery templates. This file can be downloaded from here

Grab a copy now and stick it in the same folder as the web page we just created.

I mentioned a custom style sheet earlier; let’s add that in right now; in a new file in your text editor add the following code:

#tweetbox {
	display:block; width:300px; padding:10px; border:1px solid #aaa; -moz-border-radius:5px;
	border-radius:5px; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
	background-color:#eee;
}
#tweetbox img { display:block; }
#user { margin-bottom:10px; float:left; }
#user h2 { margin:0 0 10px 0; position:relative; font-size:18px; }
#user img { float:left; }
#user p { width:230px; margin:0; position:relative; float:left; font-size:10px; color:#333; }
#user img { display:block; margin-right:10px; border:3px solid #333; }
#tools { margin:0; *margin-bottom:-10px; padding:0; clear:both; list-style-type:none; }
#tools li {  float:left; }
#tools a {
	display:block; height:20px; padding:3px 24px; border:1px solid #aaa; border-bottom:none;
	-moz-border-radius:5px 5px 0 0; border-radius:5px 5px 0 0; margin-right:-1px;
	position:relative; font-size:14px; outline:none; background-color:#d6d6d6;
	background-image:-webkit-gradient(linear, left top, left bottom, color-stop(0.5, #E8E8E8), color-stop(0, #DBDBDB), color-stop(0.5, #D6D6D6));
	background-image: -moz-linear-gradient(center top, #E8E8E8 50%, #DBDBDB 0%, #D6D6D6 50%);
}
a { text-decoration:none; color:#333; }
#tools .on { height:21px; margin-top:-1px; top:1px; }
#feed { width:298px; border:1px solid #aaa; clear:both; background-color:#d6d6d6; }
#feed > div { display:none; }
noscript { display:block; padding:10px; font-size:13px; color:#333; }

Save this file as tweetbox.css in the same directory as the HTML page. This is just a bit of layout styling for our widget. There’s a couple of CSS3 niceties for capable browsers: some rounded-corner action (notice we no longer need the –webkit- vendor prefix for rounded corners in the latest webkit browsers!) and some gradients for the tabs. A point to note is that we hide all of the containers within the feed element, except for the one with the class active. At this point (and with JS disabled) the widget should look like so:


Adding the Script

Let’s put the basic script together and get those tabs working. In another new file in your text editor, add the following code:

(function($) {
	//tabs
	var tweetbox = $("#tweetbox"),
		tweetData = null,
		friendData = null,
		followData = null;

	tweetbox.find("#tools a").click(function(e) {
		e.preventDefault();

		var link = $(this),
			target = link.attr("href").split("#")[1];

		tweetbox.find(".on").removeClass("on");
		link.addClass("on");
		tweetbox.find("#feed > div").hide();
		tweetbox.find("#" + target).show();
	});
})(jQuery);

Save this file as tweetbox.js in the same directory as the HTML page. It’s all pretty straight-forward, and, as it’s not really the main focus of this tutorial, I won’t go into it too much. All we do is alias the string character within an anonymous function, which we execute straight away – more for good-practice than sheer necessity in this example – and then cache a selector for the main outer container for the widget. We also initialize three variables for use later on, and set their values to null.

We’ll need to select elements repeatedly throughout the code; so caching a reference to the outer container helps minimise the number of jQuery objects we need to create. We then set a click handler for the tab links which gets the id of the tab to show from the href of the link that was clicked, removes the class name on from the tab links and then adds it back to the link that was clicked. We then hide all of the tab panels, before showing the selected tab panel.


Getting the Data

Now the real fun begins; we can make the requests to Twitter to get our three data sets and make use of jQuery’s templating plugin to create the required DOM elements using the data we obtain from the requests. We’ll get the data first and then add the templates. After the click-handler for the tool links, add the following code:

$.ajaxSetup({
	dataType: "jsonp"
});

function getTweets() {
	$.ajax("http://api.twitter.com/statuses/user_timeline/danwellman.json", {
		success: function(data) {
			var arr = [];

			for (var x = 0; x < 5; x++) {
				var dataItem = {};
				dataItem["tweetlink"] = data[x].id_str;
				dataItem["timestamp"] = convertDate(data, x);
				dataItem["text"] = breakTweet(data, x);
				arr.push(dataItem);
			}

			tweetData = arr;
		}
	});
}
function getFriends() {
	return $.ajax("http://api.twitter.com/1/statuses/friends/danwellman.json", {
		dataType: "jsonp",
		success: function(data) {
			var arr = [];

			for (var x = 0; x < 5; x++) {
				var dataItem = {};
				dataItem["screenname"] = data[x].screen_name;
				dataItem["img"] = data[x].profile_image_url;
				dataItem["name"] = data[x].name;
				dataItem["desc"] = data[x].description;
				arr.push(dataItem);
			}

			friendData = arr;
		}
	});
}
function getFollows() {
	return $.ajax("http://api.twitter.com/1/statuses/followers/danwellman.json", {
		dataType: "jsonp",
		success: function(data) {
			var arr = [];

			for (var x = 0; x < 5; x++) {
				var dataItem = {};
				dataItem["screenname"] = data[x].screen_name;
				dataItem["img"] = data[x].profile_image_url;
				dataItem["name"] = data[x].name;
				dataItem["desc"] = data[x].description;
				arr.push(dataItem);
			}

			followData = arr;
		}
	});
}

//execute once all requests complete
$.when(getTweets(), getFriends(), getFollows()).then(function(){

	//apply templates
});

First, we use jQuery’s ajaxSetup() method to set the dataType option to jsonp for all subsequent requests. As this will be the dataType used by each of our requests, it makes sense to just set the option once.

We then define three standard functions; within each function we use jQuery’s ajax() method to make a request to the web service that returns each set of data we’ll be working with, the user_timeline, friends and followers respectively. In the settings object for each request, we define a success handler which will be executed once each individual request returns successfully. Each of these requests will return a JSON object that potentially contains up to 100 objects packed full of Twitter data.

To ensure that the data is stored in the correct format for JSON we use square-bracket notation.

We don’t need that much data, so in each success handler we create a new array, which in turn will contain a series of objects that hold just the data we are actually going to use. To ensure that the data is stored in the correct format for JSON, where every property name must be a string, we use square-bracket notation to set the property names in string format.

The user_timeline request stores the id string of the tweet which can be used as part of a URL that points to the tweet, as well as storing the result of two utility functions. The first of these functions creates a formatted data string which converts the date returned by Twitter into something that is a little prettier, and localised to the viewer’s machine. We also format the tweet text so that we can atify any @usernames found in the text. We’ll look at both the date and tweet formatter functions shortly.

The functions to retrieve the friends and followers lists are pretty much identical. Again, we rename the properties that we’ll be working with when we build our objects and store them in each array. All three of our success handlers store the resulting 5-item arrays in the null variables we set at the top of the script.

Notice that we don’t invoke each of our getTweets(), getFriends() and getFollowers() functions manually. Instead, we use jQuery’s new when() method to invoke all of them at the same time. This method will completely handle running these functions and will keep track of when each one has returned. We chain the then() method after the when() method. Once all of the specified functions have returned successfully, the callback function we pass to the then() method will be executed.

The when() method creates a deferred object that manages the functions we specify as arguments.

Once the functions have all returned, the deferred object is resolved and any functions registered with then() are called. Other handlers may also be chained to the when() deferred object, such as fail(), which would be executed if one or more of the functions passed to the deferred object failed.

This is incredible; we want to make all three requests, but we have no way of knowing beforehand which of these will be returned last, so it is impossible to use any one request’s callback function if we wish to process the data returned from all of the functions at the same time. In the past, we would probably have had to setup an interval which repeatedly polled each function to check whether it had returned, and wait until all of them had before proceeding. Now we can delegate all of this manual tracking to jQuery to handle for us automatically.


Utility Functions

We use two utility functions in this example: convertDate() and breakTweet(). The code for these functions is as follows:

//format date
convertDate = function(obj, i) {

	//remove time zone offset in IE
	if (window.ActiveXObject) {
		obj[i].created_at = obj[i].created_at.replace(/[+]\d{4}/, "");
	}

	//pretty date in system locale
	var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
		date = new Date(obj[i].created_at),
		formattedTimeStampArray = [days[obj[i].created_at], date.toLocaleDateString(), date.toLocaleTimeString()];

	return formattedTimeStampArray.join(" ");
}

//format text
breakTweet = function(obj, i) {

	//atify
	var text = obj[i].text,
		brokenTweet = [],
		atExpr = /(@[\w]+)/;

	if (text.match(atExpr)) {
		var splitTweet = text.split(atExpr);

		for (var x = 0, y = splitTweet.length; x < y; x++) {

			var tmpObj = {};

			if (splitTweet[x].indexOf("@") != -1) {
				tmpObj["Name"] = splitTweet[x];
			} else {
				tmpObj["Text"] = splitTweet[x];
			}

			brokenTweet.push(tmpObj);
		}
	} else {
		var tmpObj = {};
			tmpObj["Text"] = text;
		brokenTweet.push(tmpObj);
	}

	return brokenTweet;
}

The convertDate() function is relatively straight-forward: we first check whether the browser in use is a variant of IE by looking for window.ActiveXObject. If this is found, we use the JavaScript replace() method to remove the Timezone Offset supplied as part of the string contained within the created_at property of the JSON object returned by Twitter. This method takes the regular expression pattern to look for, and an empty string to replace it with. This stops IE choking on the + character when the string is passed to the new Date constructor.

Next we create some variables; we set an array containing shortened day names, with Sunday (or Sun) as the first item in the array. Days in JavaScript dates are zero-based, with Sunday always appearing as day 0. We then create a Date object using the new Date() constructor, and pass in the date string stored in the created_at property of the object we passed in to the function.

We then create another array containing three items: the first item gets the correct day of the week from the first array we created within this function, the next item gets the localised date, and the last item gets the localised time. Finally, we return the contents of the array after we have joined it. We could simply use string concatenation to build this date string, but joining array items is much faster than building strings manually.

The breakTweet() function is slightly more complex. What we need to do is convert the plain text into a JSON array where each array item is an object containing either a Name or Text property so that we can use the data with a template (more on the templates next). First we store the text from the object returned by Twitter (which we pass into the function). We also create an empty array to store the objects in and define the regular expression that will match @usernames.

We then test the text to see whether it contains any usernames; if it does we then split the text string on each occurrence of a username. This will give us an array which contains items that are either plain text, or a username. We then cycle through each item in this array and check whether each item contains the @ symbol; if it does, we know it’s a username and so store it in an object with the key Name. If it doesn’t contain the @ symbol we save it with the key Text. The object is then pushed into the array. Also, if the whole text doesn’t contain an @ character we store it with the key Text.

That’s it; once we have stored our objects the function returns the new brokenTweet array to the user_timeline success function and is stored in the main JSON object for use with our templates. As well as atifying the text, we could also linkify and hashify if we wanted. I’ll leave that up to you to implement.


Templating

Now that we have our processed JSON data, we can move on to the final part of the example: templating. In the anonymous function passed to the then() method in the last code section, there was a comment and nothing else. Directly after this comment, append the following code:

//apply templates
tweetbox.find("#tweetTemplate").tmpl(tweetData).appendTo("#tweetList");
tweetbox.find("#ffTemplate").tmpl(friendData).appendTo("#friendList");
tweetbox.find("#ffTemplate").tmpl(followData).appendTo("#followList");

//show tweets
tweetbox.find("#tweets").show();

This code simply applies the templates using the jQuery templating plugin method tmpl(). The method accepts the JSON containing the data that the template will use. We then specify where in the document to insert the template elements. Each set of templates appends the elements to the respective empty container within the widget. The tmpl() method is called on three elements, but these elements don’t yet exist. We’ll add these next.


Adding the jQuery Templates

Switch back to the HTML and first add the following <script> element directly after the empty <ul> with the id tweetList:

<script id="tweetTemplate" type="text/x-jquery-tmpl">
	<li>
		<p>
			{{each text}}
				{{if Name}}
					{{tmpl(Name) "#atTemplate"}}
				{{else}}
					${Text}
				{{/if}}
			{{/each}}
			<a class="tweet-link" href="http://twitter.com/danwellman/status/${tweetlink}">${timestamp}</a>
		</p>
	</li>
</script>
<script id="atTemplate" type="text/x-jquery-tmpl">
	<a href="http://twitter.com/${$item.data}">${$item.data}</a>
</script>

jQuery templates are added to the HTML page using <script> elements. These elements should have id attributes set on them so that they can be selected and have the tmpl() method called on them. They should also have the custom type x-jquery-tmpl set on them.

In the first template, we add the mark-up that we want to new DOM structure to be built from, which in this case is an <li>, a <p> and an <a> to create each tweet. To insert the data from the JSON object passed into the tmpl() method we use a series of templating tags. First we use the {{each}} tag to go through each item in the text array.

This is the array containing the broken up tweet, so for each object we check whether it has a Name key; if it does we use the {{tmpl}} tag, which allows us to use a nested template. We specify the data to pass the nested function within parentheses after the tmpl tag and also specify the id of the template to select (this is the second template that we just added, which we’ll look at in more detail in a moment). If the object does not contain a Name property, we know that we are dealing with a plain text portion of the tweet and just insert the data using ${Text}. This conditional is achieved using the {{else}} template tag. We should also close the conditional using {{/if}, and close the iteration using {{/each}}.

Finally, we create a new anchor element that links directly to the tweet on the Twitter website using ${tweetlink} as part of the href, and ${timestamp} properties. These properties are the ones we created in the success handler for the user_timeline request.

In the atTemplate we also create a link; this time it links to the user that was mentioned. As this is a nested template, we need to access the actual data slightly differently; the data passed into the nested template by the {{tmpl} tag will be stored in a property of the $item object called data.

We still need to add the template for our friends and followers tabs. Both of these will be built from the same template, which should be as follows:

<script id="ffTemplate" type="text/x-jquery-tmpl">
	<li>
		<p>
			<a class="img-link" href="http://twitter.com/${screenname}"><img src="${img}" alt="${name}"></a>
			<span class="username"><a href="http://twitter.com/${screenname}">${screenname}</a></span>
			<span class="bio">${desc}</span>
		</p>
	</li>
</script>

This template is much simpler as we aren’t using nested templates or doing any iteration, we’re simply inserting the data from each JSON array using the ${data} template item format.


Finishing Up

Now that we applied the templates and populated our widget, we can add a few more CSS styles to tidy up the new elements that have been added; in tweetbox.css add the following code to the end of the file:

#feed ul { padding:0; margin:0; }
#feed li { padding:0; border-bottom:1px solid #aaa; list-style-type:none; font-size:11px; }
#feed li:last-child, #feed li:last-child p { border-bottom:none; }
#feed p { padding:10px; margin:0; border-bottom:1px solid #eee; background-image:-webkit-gradient(linear, left bottom, left top, color-stop(0.48, #c2c2c2), color-stop(0.71, #d6d6d6)); background-image:-moz-linear-gradient(center bottom, #c2c2c2 48%, #d6d6d6 71%); }
#feed p:after { content:""; display:block; width:100%; height:0; clear:both; }
.tweet-link { display:block; margin-top:5px; color:#777; }
.img-link { display:block; margin:4px 10px 0 0; float:left; }
#feed .username a { font-size:14px; font-weight:bold; }
#feed .bio { display:block; margin-top:10px; }

Save the file, our page should now appear as follows:

There’s still one more thing we should probably do: at the moment, our tweet formatting function doesn’t work in IE because of how IE treats the split() regular expression method. To fix this issue, we can use an excellent JavaScript patch created by Steven Levithan. It can be downloaded from: http://blog.stevenlevithan.com/archives/cross-browser-split and can be included in the page using a conditional comment in the same way that we added the html5shiv file:

<!--[if IE]>
	<script src="fixSplit.js"></script>
<![endif]-->

This should be added directly before the script reference to our tweetbox.js file.


Summary

In this tutorial we looked at some of the more advanced features of jQuery templating, such as item iteration with {{each}} and conditionals with {{if}} and {{else}}.

A key point is that the new templating system from jQuery allows us to better separate our behaviour and presentation layers, moving all HTML snippets out of the .js file and back into the .html file.

Some might argue that we now just have the opposite situation and simply have more <script> in our page.

However, I think this is infinitely preferable to the alternative. Elements in the format $("<div>") are simply strings with no implicit meaning (until jQuery is run by the browser and they are created and inserted into the DOM).

We also looked at the excellent new when() method provided in jQuery 1.5, which allows us to manage a set of asynchronous requests and execute code once they have all completed. This involves using the then() method to specify a function to execute once the asynchronous functions have all returned.

Thank you so much for reading and let me know if you have any questions!

February 16 2011

22:00

ASP.NET and AJAX


In this tutorial, we’ll take a look at some of the things you can do with ASP.NET and AJAX in your web applications. It’s more than just wrapping an UpdatePanel around some buttons, textboxes and grids!


Asynchronous JavaScript and XML

There are many caveats with arbitrarily dropping UpdatePanels onto webforms and hoping for the best.

Though this tutorial will focus primarily on other components besides the UpdatePanel, it might be useful to take a look at postback triggers as well. Wrapping some controls on a webform in an UpdatePanel is a cheap and cheerful way of implementing Ajax.

Postbacks caused by the web controls in the UpdatePanel should happen asynchronously and not cause an entire page postback. There are, however, many caveats with arbitrarily dropping UpdatePanels onto webforms and hoping for the best.

There are also situations in which one may want to conditionally cause a postback of the entire page, or perhaps just make one method call to a backend method or web service to update some small part of the page.


UpdatePanel

An UpdatePanel control specifies what regions of a page can be updated asynchronously.

Let’s start by looking at a simple UpdatePanel control and some of the things it can do out of the box. The control specifies what regions of a page can be updated asynchronously, and thus not require an entire postback of the page.

Create a new ASP.NET Web Application project. To your default.aspx page, add a ScriptManager control, a TextBox control called txtOutsideUpdatePanel, and an UpdatePanel. Add a ContentTemplate to the UpdatePanel, and, within it, add a Button control called btnInsideUpdatePanel, and a TextBox control called txtInsideUpdatePanel. Below are the salient lines from the source view:

<div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:TextBox ID="txtOutsideUpdatePanel" runat="server"></asp:TextBox>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button runat="server" Text="Update" ID="btnInsideUpdatePanel" />
            <asp:TextBox runat="server" ID="txtInsideUpdatePanel"></asp:TextBox>
        </ContentTemplate>
    </asp:UpdatePanel>
</div>

Next, add the following code to the code-behind for the page (or to the script tag if you’re not using the code-behind):

Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        txtOutsideUpdatePanel.Text = Now.ToString
    End Sub

    Protected Sub btnInsideUpdatePanel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnInsideUpdatePanel.Click
        txtInsideUpdatePanel.Text = Now.ToString
    End Sub
End Class

View the page in your web browser, and you should see two textboxes on the webform. The first textbox should have a date and time in it. If you refresh the page, the first textbox should update its date and time. Press the button, and only the second textbox should refresh its date and time. Thus the button is causing an asynchronous postbox, because it’s within the UpdatePanel.

What we’ve done so far is the easy way of Ajax’ifying a webform. We could easily put an entire grid with paging support within the UpdatePanel for flicker-less paging.

Let’s look at all this in a little more detail.


Controlling UpdatePanel Updates

We can control when the UpdatePanel control posts back based on events that occur to controls both inside and outside the panel itself. Here is the properties window:

There are three properties of interest to us at present:

  • UpdateMode: Always (default) or Conditional
  • ChildrenAsTriggers: True (default) or False
  • Triggers: A collection of controls – discussed further below

There are three valid combinations of UpdateMode and ChildrenAsTriggers:

  • Always =True UpdatePanel will refresh when the whole page refreshes, or when a child control posts back.
  • Always = False (invalid)
  • Conditional = True UpdatePanel will refresh when the whole page refreshes, or when a child control posts back, or a trigger from outside of the UpdatePanel causes a refresh.
  • Conditional = False UpdatePanel will refresh when the whole page refreshes, or a trigger outside of the UpdatePanel causes a refresh. A child control will not cause a refresh.

The next property we’re interested in is the Triggers property, which comes in two flavours:

  • AsyncPostBackTrigger: Causes an asynchronous refresh of the UpdatePanel
  • PostBackTrigger: Causes a page postback by a child control of the UpdatePanel

Let’s take a look at how these affect the functionality of the UpdatePanel. Paste the following code into a webform, and then the VB.Net code below that into the code-behind.

We have two buttons inside the panel and two buttons outside. We have wired up the triggers such that a button inside will cause a full page postback, and a button will cause an asynchronous refresh.

    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnAsyncTrigger" />
            <asp:PostBackTrigger ControlID="btnPostBackTrigger" />
        </Triggers>
        <ContentTemplate>
            <asp:Label ID="lblInnerTime" runat="server"></asp:Label>
            <br />
            <asp:Button ID="btnInnerTime" runat="server" Text="Inner Time" />
            <asp:Button ID="btnPostBackTrigger" runat="server" Text="PostBack Trigger" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <br />
    <br />
    <asp:Label ID="lblOuterTime" runat="server"></asp:Label>
    <br />
    <asp:Button ID="btnOuterTime" runat="server" Text="Outer Time" />
    <asp:Button ID="btnAsyncTrigger" runat="server" Text="Async Trigger" />
    </form>

Code-behind:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        lblInnerTime.Text = Now
        lblOuterTime.Text = Now
    End Sub

The webform should look as follows:

Clicking the Inner Time button will cause an asynchronous postback. This is expected, as the button is within the UpdatePanel. Clicking the Outer Time button will cause a full page postback. Again, this is expected, as the Outer Time button is outside the panel.

The two interesting cases are the PostBack trigger and Async Trigger buttons, to which we make reference in the triggers section of the UpdatePanel. When defining triggers, we need to specify the ControlID of the control acting as a trigger, and optionally the event for which the trigger should fire. If we omit the event, it will fire on the default event for that control.

Conditional UpdatePanel Updates

By setting the UpdateMode property of the UpdatePanel to Conditional, and ChildrenAsTriggers to False we can control when updates will be performed. An asynchronous postback will still be performed, but we can decide when to send the updated HTML content for that region of a page to the browser.

Paste the following code into an ASPX page:

    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False" >
            <ContentTemplate>
                <asp:Label ID="lblDateTime" runat="server" Text=""></asp:Label><br />
                <asp:Button ID="btnAsyncPostBack1" runat="server" Text="Inside UpdatePanel 1" />
                <asp:Button ID="btnAsyncPostBack2" runat="server" Text="Inside UpdatePanel 2" />
            </ContentTemplate>
        </asp:UpdatePanel>
        <br />
        <asp:Button ID="btnSyncPostBack" runat="server" Text="Outside UpdatePanel" />
    </div>
    </form>

And the following code into its code behind:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lblDateTime.Text = Now
    End Sub

    Protected Sub btnAsyncPostBack1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAsyncPostBack1.Click
        'Do Nothing
    End Sub

    Protected Sub btnAsyncPostBack2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAsyncPostBack2.Click
        UpdatePanel1.Update()
    End Sub

You should get a form that looks like the following:

  • Clicking on the Inside UpdatePanel 1 button will cause an asynchronous postback to occur, but the UpdatePanelwon’t be updated.
  • Clicking on the Inside UpdatePanel 2 button will cause an asynchronous postback to occur, and we are explicitly updating the panel.
  • Clicking on the Outside UpdatePanel will cause a normal full page postback.

Timers

We can cause postbacks to occur periodically by using an ASP.NET timer control. This is useful for any regions of a webform that needs live/current data to be visible, such as news feeds or live stock numbers. The Timer.Tick event is fired at an interval defined by the Interval property, which is in milliseconds. It is the Tick event that we can use to cause asynchronous or full page postbacks.

The way in which the timer control influences the panel can be controlled using the Triggers collection.

  • As a child control of the UpdatePanel, with no triggers defined: refreshes asynchronously on Timer.Tick
  • Outside, with no triggers defined: Entire page posts back on Timer.Tick
  • As a child control, with a PostBackTrigger defined: Entire page posts back on Timer.Tick
  • Outside, with an AsyncPostBackTrigger defined: UpdatePanel refreshes asynchronously on Timer.Tick

ASP.NET Ajax Client Library

When you add a ScriptManager control to a webform, it makes the ASP.NET Client Library JavaScript files available to the user’s browser.

The JavaScript files are taken from the System.Web.Extensions assembly. Visual Studio’s Intellisense will also pick up the functionality exposed by the client library at design time.

Add a ScriptManager to a webform, add a new <script> tag, type Sys. and you should see a whole host of new bits and pieces to play with. We’ll look at some of the namespaces exposed below.

The examples consist mostly of JavaScript code, which belongs in a <script> tag.

Ajax Client Library Namespaces

  • Global Namespace
  • Sys
  • Sys.Net
  • Sys.Serialization
  • Sys.Services
  • Sys.UI
  • Sys.WebForms

Global Namespace

The client library provides us with some extensions to existing JavaScript objects. The extensions should make working with JavaScript objects feel a little more like working with managed code. We can also very easily extend existing JavaScript objects ourselves. In addition to extending the functionality of JavaScript objects, the client library also automatically wires up a number of events that we can very easily hook into.

Arrays:

Here we are using the sort() and join() extension methods:

    var unsortedArray = [5, 4, 3, 2, 1];
    var sortedArray = unsortedArray.sort();
    alert(sortedArray.join(','));

Here we are extending the Array object by adding a min() method:

    function minElement() {
        var minimum = Infinity;
        for (var i = 0; i < this.length; i++) {
            if (this[i] < minimum) {
                minimum = this[i];
            }
        }
        return minimum;
    }

    var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    Array.prototype.min = minElement;
    alert(myArray.min());

And here we are adding elements to an array:

    var myArray1 = [1, 2, 3];
    var myArray2 = [5, 6, 7];

    Array.add(myArray1, 4);
    Array.addRange(myArray2, [8, 9]);

Sys.Debug

We can use the Sys.Debug.trace() method to display messages in the debugger. This is useful if you want to avoid using alert() calls all over your pages. The debugger messages appear in the Output window in Visual Studio during a debugging session. So this means that you need to "run" the web project and visit the page, or attach to an existing w3p process.

In the piece of code below, we have a simple loop which causes a divide by zero, which might cause issues in subsequent calculations. By using trace(), we can print out the current value of the counter variable as the loop is running:

    var counter = 10;
    while (counter >= 0) {
        counter -= 1;
        Sys.Debug.trace("Current value of counter = " + counter);
        var someCalculatedValue = 10 / counter;
        document.write(someCalculatedValue + " ");
    }

Now let's use it to help us design and test a new JavaScript object:

    Employee = function(employeeId, name) {
        this.EmployeeId = employeeId;
        this.Name = name;
    }
    Employee.prototype = {
        toString: function () {
            return this.EmployeeId + " : " + this.Name;
        },
        get_Name: function () {
            return this.Name;
        },
        set_Name: function (newName) {
            this.Name = newName;
        }
    }
    Employee.registerClass("Employee");

    var jamie = new Employee(123, "Jamie Plenderleith");
    Sys.Debug.trace("Before name change : " + jamie.Name);

    jamie.Name = "Jamie Plenderleith Esq.";
    Sys.Debug.trace("After name change : " + jamie.Name);

Events

The client library wires up some page events that we can hook into easily. Page-specific events are as follows:

  • pageLoad
  • pageUnLoad

And then we can access some events wired up to the PageRequestManager object which are related to asynchronous postbacks:

  • InitializeRequest
  • BeginRequest
  • PageLoading
  • PageLoaded
  • EndRequest

Let's use trace() to see when these events fire:

    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="Button1" runat="server" Text="Button" />
            </ContentTemplate>
        </asp:UpdatePanel>
        <script language="javascript" type="text/javascript">
            var myPageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
            myPageRequestManager.add_initializeRequest(onInitializeRequest);
            myPageRequestManager.add_beginRequest(onBeginRequest);
            myPageRequestManager.add_pageLoading(onPageLoading);
            myPageRequestManager.add_pageLoaded(onPageLoaded);
            myPageRequestManager.add_endRequest(onEndRequest);

            function pageLoad(sender, args) {
                Sys.Debug.trace("pageLoad()");
            }

            function onInitializeRequest(sender, args) {
                Sys.Debug.trace("PageRequestManager.InitializeRequest");
            }
            function onBeginRequest(sender, args) {
                Sys.Debug.trace("PageRequestManager.BeginRequest");
            }
            function onPageLoading(sender, args) {
                Sys.Debug.trace("PageRequestManager.PageLoading");
            }
            function onPageLoaded(sender, args) {
                Sys.Debug.trace("PageRequestManager.PageLoaded");
            }
            function onEndRequest(sender, args) {
                Sys.Debug.trace("PageRequestManager.EndRequest");
            }

            function pageUnload(sender, args) {
                Sys.Debug.trace("pageUnload()");
            }
        </script>
    </div>
    </form>

We could even cancel an asynchronous postback if we want to:

    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="btnUpdateDateTime" runat="server" Text="Update" />
                <asp:Label ID="lblDateTime" runat="server" Text=""></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
        <script language="javascript" type="text/javascript">
            var myPageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
            myPageRequestManager.add_initializeRequest(onInitializeRequest);

            function onInitializeRequest(sender, args) {
                var someCondition = false;

                if (!someCondition) {
                    Sys.Debug.trace("someCondition=false. Aborting postback");
                    args.set_cancel(true);
                }
            }
        </script>
    </div>
    </form>

Remote Method Calls

If the user has a particularly large ViewState, this will cause a lot of extra overhead for both them and the webserver. The remote aspx page will go through nearly its complete lifecycle from loading through to unloading.

Now we'll take a look at making calls to specific remote methods. These exist entirely separate to the UpdatePanelcontrol, but they'll probably be used in conjunction in order to display the result of some method call.

When an asynchronous postback occurs within the control, a full postback of the page's ViewState is sent to the webserver. So if the user has a particularly large ViewState, this will cause a lot of extra overhead for both them and the webserver. In addition to the ViewState, the remote aspx page will go through nearly its complete lifecycle from loading through to unloading. We can interface with .NET 2.0 ASP.NET Web Services, .Net 4.0 WCF Services (which act like .Net 2.0 ASP.NET Web Services when using HTTP Transport anyway) and with ASP.NET WebForms PageMethods. We'll take a look at using PageMethods.

ASPX Page Methods

A Page Method is a public shared (static in C#) method defined in a webform decorated with System.Web.Services.WebMethod(). In addition to decorating your methods appropriately, your ScriptManager must have its EnablePageMethods property set to True. From there you should see the method available through the PageMethods proxy class in JavaScript.

Here is a very simple example of a call to managed code to perform a calculation. Paste the following into the source view of a webform:

    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        y = log <sub>b</sub>(x)<br />
        Base b =
        <input id="txtBase" type="text" /><br />
        Value x =
        <input id="txtValue" type="text" /><br />
        Result y = <span id="lblResult"></span>
        <br />
        <input id="btnCalculate" type="button" value="Calculate" />
        <script language="javascript" type="text/javascript">
            $addHandler($get('btnCalculate'), "click", btnCalculate_onclick);

            function btnCalculate_onclick() {
                PageMethods.CalculateLog($get('txtBase').value, $get('txtValue').value, calculateLog_Finished, calculateLog_Failed);
            }

            function calculateLog_Finished(result) {
                $get('lblResult').innerText = result;
            }

            function calculateLog_Failed(errObj) {
                Sys.Debug.trace(errObj.get_message());
            }
        </script>
    </div>
    </form>
    

And to the code-behind file add the following code:

    <System.Web.Services.WebMethod()> Public Shared Function CalculateLog(ByVal Value As Double, ByVal Base As Double) As Double
        Return Math.Log(Value, Base)
    End Function
    

You can see it's a very simple call to the Math.Log() method, but it's executed asynchronously without requiring a postback, and without the use of an UpdatePanel. Observe the PageMethods.CalculateLog() method call. It takes the two parameters required by the method in the code-behind. In the example above, the next parameter is the callback to execute upon successful completion of the method call, and the last parameter is the callback to execute when an error occurs.

A caveat on PageMethods however: If the class does not appear for you in the JavaScript, you can try a few things:

  • Ensure your code-behind method is Public Shared
  • Ensure there are no JavaScript syntax errors
  • Ensure the ScriptManager's EnablePageMethods property = True
  • Remove and re-add the ScriptManager
  • Perform a rebuild

A more complete syntax for a PageMethod method call is as follows:

    PageMethods.MethodName(Param1, Param2 ... , ParamN, CompletionCallback, FailureCallback, ContextParameter)

Consider our original calculateLog_Finished() method signature:

    function calculateLog_Finished(result) {}

This method can take additional parameters:

    function calculateLog_Finished(result, context, method) {}
  • Result: The result of the method call
  • Context: The value of ContextParameter originally passed by the PageMethods proxy,
    if any
  • Method: The method that was invoked - useful when sharing callbacks

Further Reading

There are a plethora of aspects related to Ajax that we haven't touched on. Nonetheless, the following may be of interest to you in your projects:

Thanks for reading!

November 18 2010

10:00

30 Awesome Ajax Lightbox and Modal Dialog Solutions

Modal Dialog and Lightbox are Ajax solutions for displaying the content inside the browser without reloading the whole page. Lightboxes overcome the use of the pop up window to suit on the modern browsers and it is being used everywhere these days.  It is widely used for  displaying of media files, webpages , messages, forms etc in a nice looking overlay.

In this post, I’ll be featuring 30 awesome lightbox and modal dialog boxes that you can use on you web applications.

1. Facebox

Facebox is a jQuery-based, Facebook-style lightbox which can display images, divs, or entire remote pages. It’s simple to use and easy on the eyes.

2. Lightbox2

Lightbox is a simple, unobtrusive script used to overlay images on the current page. It’s a snap to setup and works on all modern browsers.

3. Fancybox

FancyBox is a tool for displaying images, html content and multi-media in a Mac-style “lightbox” that floats overtop of web page.

4. Colorbox

A light-weight, customizable lightbox plugin for jQuery 1.3 and 1.4. Supports photos, grouping, slideshow, ajax, inline, and iframed content.

5. jQuery Lightbox Plugin

jQuery lightBox plugin is simple, elegant, unobtrusive, no need extra markup and is used to overlay images on the current page through the power and flexibility of jQuery´s selector.

6. prettyPhoto

prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes.

7. Litebox

Lightweight lightbox which built on moo.fx and prototype.lite.

8. Thickbox

It has more features than lightbox2  like display inline content, iframed content or content served through ajax in a hybrid modal.

9. Slimbox

It was designed to be very small, efficient, standards-friendly, fully customizable, more convenient and 100% compatible with the original Lightbox 2.

10. LightView

Lightview was built to change the way you overlay content on a website that supports multiple media files.

11. jQuery Dialog

Query UI contains dialog component. It can be customized to create your own taste of image preview or gallery.

12. Prototype Window

Prototype window based dialog boxes.

13. MochaUI

MochaUI is a web applications user interface library built on the Mootools JavaScript framework.

14. Boxy

Boxy is a flexible, Facebook-style dialog box for jQuery with support for dragging and size tweening.

15. ModalBox

It’s inspired by Mac OS X modal dialogs.

16. Shadowbox

Shadowbox is a web-based media viewer application that supports all of the web’s most popular media publishing formats. Shadowbox is written entirely in JavaScript and CSS and is highly customizable.

17. LightWindows

A lightbox solutions that enable you to embed images, video,iFrame, flash and more.

18. SimpleModal

impleModal gives you the flexibility to build whatever you can envision, while shielding you from related cross-browser issues inherent with UI development.

19. jqModal

jqModal is a plugin for jQuery to help you display notices, dialogs, and modal windows in a web browser. It is flexible and tiny, akin to a “Swiss Army Knife”, and makes a great base as a general purpose windowing framework

20. Multibox

It support images,flash, video, mp3 and html and it is built with mootools.

21. Greybox

GreyBox can be used to display websites, images and other content in a beautiful way.

22. Highslide

Highslide JS is an image, media and gallery viewer written in JavaScript. It has a quick and elegant looking.

23. Sexybox

Lightbox that display content directly from html.

24. PiroBox

Stylish and modern jquery lightbox.

25. Super Box

Super Box is a script which allows you display windows with the lightbox effect.

26. CeeBox

It is an overlay popup script that embeds flash video, display images, or show html.

27. NyroModal

Modal box that uses callback animation and a lot more features.

28. imgBox

mgBox is a jQuery plugin that implements a smooth zoom effect on images.

29. ClearBox

Clearbox is a professional image and content viewer overlay window.

30. jQuery Tools

jQuery Tools is a collection of most user interface components for modern websites such as lightboxes.

Choose the appropriate lightbox or modal box on your website.  Next time your users visit they will be attracted on these modern trend and design for your website.

October 26 2010

21:00

Asynchronous Technologies: AJAX, AJAH, AHAH, and AJAJ

AJAX, AJAH, AHAH, and AJAJHey guys and gurls! Today we are going to take a look at different asynchronous technologies. There are many variations of them over the net. They’re AJAX, AJAH, AHAH, and AJAJ.
AJAX (Asynchronous Javascript and XML) – is a technology for asynchronous data transmission between the browser and the server. Asynchrony implies the data transfer without reloading the page. In other words, you can respond to user actions more quickly, making your applications more interactive. For example, in the sign-up form checking login for employment can be performed immediately after the login is entered without updating the page (I think all have met with such).

Introduction

Before we get started, i’ll tell you a little bit more about data transfer solutions… The title AJAX referred to XML, although at present, for asynchronous data transmission, it is used less frequently (in pure form, at least). In addition to XML, there are HTML (a technology called AJAH), HTML + HTTP (AHAH) and Javascript + JSON (AJAJ).

I will lead examples using jQuery JS framework. jQuery supports all three types of asynchronous data transfer.

There is a lot of features to work with AJAX in jQuery, but the main ones being. get () and. gost (). Their syntax looks like:

	$.post(url[, params[, callback]])
	$.get(url[, params[, callback]])

where, url – the address where we should send the POST (GET) request to,
params – the parameters (param1: value1, param2: value2),
callback – function to be executed after the page returns the answer for the query (as an argument it is passed the answer).

Examples

index.html

		function LoadPhpVersion() {
			$.post('version.php', {}, show_version);
		}

		function show_version(version) {
			$('#version_box').html(version);
		}

		AJAX it!
		Your php version is :

version.php

    echo phpversion();

Also in the directory with these files we should have jQuery library: jquery.js.

In this example, we just sent a POST request without parameters to the version.php script, which returned in response to our request your PHP version. A show_version() function displayed her to the html page.
As you can see everything is very simple. But in our case, everything can be even simpler :)

Using AHAH

In the previous example, the result of our request was received by the html-code (just text), which just lead to the desired location. This operation is very frequently used when templater and AJAX are working together (ie AHAH).

To use it with AHAH jQuery has a method called load().
Let’s get rewrite the previous example, but this time we will use the AHAH.

index.html

		function ShowVersion(elem_id) {
			$('#'+elem_id).load('version.php');
		}

		AJAX it!
		Your php version is :

version.php

   echo phpversion();

In this example, the javascript code is considerably reduced. As you can see, for the method load(), we should simply specify the element where we fetch the result and give him the name of the script that will send a request to.
Things got even easier.

As an example here are AHAH tests with internal javascripts

  • jQuery – page load ~ 36.7 second

jQuery - page load

  • Fullajax (Fullajax = AJAX + AHAH) – page load ~ 3.5 second

AJAX + AHAH - page load

AJAJ

Finally we consider another, very convenient data format – JSON.
Using this format and technology (AJAJ in jQuery), it is possible to transmit data to the PHP is not one piece, as object fields. So, you can return multiple variables at a time.

Working with AJAJ in jQuery is implemented through the method called getJSON();

A quick example

index.html

		function GetVersion() {
			$.getJSON('version.php', {}, function(obj){
				$('#version_box').html(obj.version);
				$('#text_box').html(obj.text);
			});
		}

		AJAX it!
		Your php version is :
		Text :

version.php

    version: '',
    text: 'Hello'

In this example, on server side two variables are generated in JSON format: version, text and displayed.

On the client side (browser side), this block is transformed into an object (via the function eval() ) with two fields – obj.version and obj.text.

By the way, jQuery has an other useful method: getScript(), which looks like:

	$.getScript(‘script.js’);

This code loads script.js file from the server and executes its code in the browser.

Final Notes

P.S. When developing applications using AJAX, I strongly recommend using Firefox with the Firebug plugin (very easy and comfortable to track the headers sent from the browser to the client asynchronously).

Feel free to download the example files by clicking [HERE].

That’s all; I hope you enjoyed this article, and thanks for reading! As always, your comments and questions are welcome!

October 19 2010

19:20

Using Unobtrusive JavaScript and AJAX with Rails 3


As I mentioned in my previous Ruby on Rails tutorial, Unobtrusive JavaScript (UJS) is one of the coolest new features in Rails 3. UJS allows Rails-generated code to be much cleaner, helps separate your JavaScript logic from your HTML layouts, and uncouples Rails from the Prototype JavaScript library. In this tutorial, we’re going to look at these features and learn how to use them in a simple Rails 3 application.


Background: What is Unobtrusive JavaScript?

To start off, what exactly is UJS? Simply, UJS is JavaScript that is separated from your HTML markup. The easiest way to describe UJS is with an example. Take an onclick event handler; we could add it obtrusively:

<a href='#' onclick='alert("Inline Javscript")'>Link</a>

Or we could add it unobtrusively by attaching the event to the link (using jQuery in this example):

<a href='#'>Link</a>
<script>
$('a').bind('click', function() {
    alert('Unobtrusive!');
}
</script>

As mentioned in my introduction, this second method has a variety of benefits, including easier debugging and cleaner code.

“Rails 3, on the other hand, is JavaScript framework agnostic. In other words, you can use your JavaScript framework of choice, provided a Rails UJS implementation exists for that framework.”

Up until version 3, Ruby on Rails generated obtrusive JavaScript. The resulting code wasn’t clean, but even worse, it was tightly coupled to the Prototype JavaScript framework. This meant that unless you created a plugin or hacked Rails, you had to use the Prototype library with Rail’s JavaScript helper methods.

Rails 3, on the other hand, is JavaScript framework agnostic. In other words, you can use your JavaScript framework of choice, provided a Rails UJS implementation exists for that framework. The current UJS implementations include the following:

Rails 3 now implements all of its JavaScript Helper functionality (AJAX submits, confirmation prompts, etc) unobtrusively by adding the following HTML 5 custom attributes to HTML elements.

  • data-method – the REST method to use in form submissions.
  • data-confirm – the confirmation message to use before performing some action.
  • data-remote – if true, submit via AJAX.
  • data-disable-with – disables form elements during a form submission

For example, this link tag

<td><a href="/posts/2" class="delete_post" data-confirm="Are you sure?" data-method="delete" data-remote="true" rel="nofollow">Destroy</a></td>

would send an AJAX delete request after asking the user “Are you sure?.”

You can imagine how much harder to read that would be if all that JavaScript was inline.

Now that we’ve reviewed UJS and how Rails implements UJS, let’s set up a project and look at some specific applications. We’ll be using the jQuery library and UJS implementation in this tutorial.


Step 1: Setting up the Project

Since we’re creating a new project from scratch, the first thing we need to do is create the project by typing the following:

	rails new blog --skip-prototype

Notice that I’m instructing Rails to skip the prototype JavaScript file, since I’m going to be using the jQuery library.

Let’s start the server just to make sure everything appears to be working.

And, voila!

Now that we’ve set up our project, we need to add jQuery and the jQuery UJS to our project. You are free to organize your JavaScript however you want, but the Rails convention for structuring your JavaScript files is as follows (all these files go in public/javascripts):

  • framework JavaScript file (jquery.js, prototype.js, or mootools.js)
  • rails.js – the code implementing rails UJS (for whatever framework you’ve chosen)
  • application.js – your application JavaScript

If you haven’t already, download jquery.js (or refer to a CDN) and rails.js and include them in your public/javascripts directory.

The last thing we need to do to get up and running is to actually tell Rails to include these js files on each of our pages. To do this, open application.rb in your config directory and add the following line

config.action_view.JavaScript_expansions[:defaults] = %w(jquery rails application)

This configuration item tells Rails to include the three JavaScript files mentioned above by default.

Alternatively, you could grab jQuery from a CDN (i.e. http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js) by manually included a script tag pointing to the correct location. If you do this, be sure to remove ‘jquery’ from the JavaScript_expansions configuration item.


Step 2: Generating Some Code

To demonstrate the rails UJS functionality, we’re first going to have to have some code to work with. For this demo we’re just going to have a simple Post object. Let’s generate that now

	rails generate scaffold Post name:string title:string content:text

And then let’s migrate our database to create the posts table.

	rake db:migrate

Ok, we’re good to go! If we navigate to http://localhost:3000/posts/new, we should see a form to create a new Post.

Ok, it’s all working! Now let’s dig in and see how to use the UJS and AJAX functionality baked into Rails.


Step 3: Adding AJAX

Now that all the required JavaScript files are being included, we can actually start using Rails 3 to implement some AJAX functionality. Although you can write all of the custom JavaScript that you want, Rails provides some nice built-in methods that you can use to easily perform AJAX calls and other JavaScript actions.

Let’s look at a couple of commonly used rails helpers and the JavaScript they generate

AJAX Form Submission and Javascript ERB Files

If we look at our Posts form, we can see that whenever we create or edit a Post, the form is manually submitted and then we’re redirected to a read-only view of that Post. What if we wanted to submit that form via AJAX instead of using a manual submission?

Rails 3 makes it easy to convert any form to AJAX. First, open your _form.html.erb partial in app/views/posts, and change the first line from:

<%= form_for(@post) do |f| %>

to

<%= form_for(@post, :remote => true) do |f| %>

Prior to Rails 3, adding :remote => true would have generated a bunch of inline JavaScript inside the form tag, but with Rails 3 UJS, the only change is the addition of an HTML 5 custom attribute. Can you spot it?

<form accept-charset="UTF-8" action="/posts" class="new_post" data-remote="true" id="new_post" method="post">

The attribute is data-remote="true", and the Rails UJS JavaScript binds to any forms with that attribute and submits them via AJAX instead of a traditional POST.

That’s all that’s needed to do the AJAX submit, but how do we perform a callback after the AJAX call returns?

The most common way of handling a return from an AJAX call is through the use of JavaScript ERB files. These work exactly like your normal ERB files, but contain JavaScript code instead of HTML. Let’s try it out.

The first thing we need to do is to tell our controller how to respond to AJAX requests. In posts_controller.rb (app/controllers) we can tell our controller to respond to an AJAX request by adding

format.js

in each respond_to block that we are going to call via AJAX. For example, we could update the create action to look like this:

def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to(@post, :notice => 'Post created.') }
        format.js
      else
        format.html { render :action => "new" }
        format.js
      end
    end
end

Because we didn’t specify any options in the respond_to block, Rails will respond to JavaScript requests by loading a .js ERB with the same name as the controller action (create.js.erb, in this case).

Now that our controller knows how to handle AJAX calls, we need to create our views. For the current example, add create.js.erb in your app/views/posts directory. This file will be rendered and the JavaScript inside will be executed when the call finishes. For now, we’ll simply overwrite the form tag with the title and contents of the blog post:

	$('body').html("<h1><%= escape_JavaScript(@post.title) %></h1>").append("<%= escape_JavaScript(@post.content) %>");

Now if we create a new Post we get the following on the screen. Success!

The advantage of this method is that you can intersperse ruby code that you set up in your controller with your JavaScript, making it really easy to manipulate your view with the results of a request.

AJAX Callbacks Using Custom JavaScript Events

Each Rails UJS implementation also provides another way to add callbacks to our AJAX calls – custom JavaScript events. Let’s look at another example. On our Posts index view (http://localhost:3000/posts/), we can see that each post can be deleted via a delete link.

Let’s AJAXify our link by adding :remote=>true and additionally giving it a CSS class so we can easily find this POST using a CSS selector.

<td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete, :remote=>true, :class=>'delete_post' %></td>

Which produces the following output:

<td><a href="/posts/2" class="delete_post" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a></td>

Each rails UJS AJAX call provides six custom events that can be attached to:

  • ajax:before – right before ajax call
  • ajax:loading – before ajax call, but after XmlHttpRequest object is created)
  • ajax:success – successful ajax call
  • ajax:failure – failed ajax call
  • ajax:complete – completion of ajax call (after ajax:success and ajax:failure)
  • ajax:after – after ajax call is sent (note: not after it returns)

In our case we’ll add an event listener to the ajax:success event on our delete links, and make the deleted post fade out rather than reloading the page. We’ll add the following JavaScript to our application.js file.

	$('.deletePost').bind('ajax:success', function() {
		$(this).closest('tr').fadeOut();
	});

We’ll also need to tell our posts_controller not to try to render a view after it finishes deleting the post.

  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to(posts_url) }
      format.js   { render :nothing => true }
    end

Now when we delete a Post it will gradually fade out.


Conclusion

Well, there you have it. Now you know how to make AJAX calls using Rails 3 UJS. While the examples explained were simple, you can use these same techniques to add all kinds of interactivity to your project. I hope you’ll agree that it’s a big improvement over previous versions, and that you’ll try it out on your next Rails project.

What techniques do you use when implementing AJAX in Rails?

September 21 2010

14:45

Create a Dojo-Powered WordPress Website View

In this article, David shows us how to use the power of Dojo and Dijit to create a stylish, AJAX-powered web app which provides intelligent views of all of my blog posts. You wont want to miss this post!

View and Vote


September 17 2010

21:47

Progressively Enhance a Form to a Modal Form


With something as important as a contact form, you want it working properly for all visitors—even the JavaScript challenged. How do you handle this if you want to use a modal (pop-up) form? The answer is progressive enhancement; start with baseline, usable functionality; then increase the user experience for those who have browsers to support it.


Step 1: Decide on the Project Goals

Before starting any journey, it helps (most times) to have a destination. The goal of this project is to take a standard link to a page containing a contact form and enable that form to pop-up on the current page in a modal dialog.

There’s several reasons for this approach:

  • If the user has JavaScript disabled, they are sent to the contact form page as usual.
  • Only one version of the form must be maintained.
  • The additional content (the form) can be loaded asynchronously.
A Modal Form

Step 2: List the Tools

To write this from scratch in raw JavaScript would be a lot of code. Fortunately for us, there are existing tools we can leverage to make the task easier. This tutorial relies on:

To make this code as reusable as possible, we’ll write a plug-in. If you are unfamiliar with authoring a plug-in, you can get an introduction from Jeffrey Way’s article here on Nettuts+. The modal functionality will come from jQuery-UI’s $.dialog.

Plug-In Theory

Step 3: Design the Plug-in Interface

We’re going to follow the normal pattern for a jQuery plug-in: calling the plug-in on a selector and setting options via array. What options are needed? There will be options both for the modal window and for the plug-in itself. We’re going to expect the plug-in to be called on an anchor, and enforce that in the code.

$('a.form_link').popUpForm({
        container   : '',
        modal       : true,
        resizeable  : false,
        width       : 440,
        title       : 'Website Form',
        beforeOpen  : function(container) {},
        onSuccess   : function(container) {},
        onError     : function(container) {}
});

Examining the options

Container: This is how the plug-in user will specify the ID of the form on the remote page. The link itself specifies the page, but container option will allow us to fetch the relevant part. This will be the only required option when calling the plug-in.

Modal, Resizeable, Width, Title: These options are all going to be passed along to jQuery UI’s $.dialog. The values above are defaults and the plug-in will run just fine without any of these being set when $.popUpForm is called.

beforeOpen, onSuccess, onError: These are all callbacks, and expect a function. The function will be passed the object for the link that was clicked as ‘this’ and the container to which that link is targeted. Callbacks are designed to allow custom functionality for the users of a plug-in. The default for these callbacks will be an empty function.

The minimum code required to use the plug-in would then look like this:

$('a.form_link').popUpForm({ container : '#form_id' });

That seems simple, doesn’t it? When you call a plug-in like this, the plug-in’s code is called with a jQuery collection of all the DOM elements matching the selector, which will be available in the special variable ‘this’.


Step 4: The Plug-In’s Skeleton

Most jQuery plug-ins follow a very similar pattern. They iterate over the group of selectors and do whatever it is they do. I’ve got a basic plug-in “outline” I generally work from, and it will fit in here nicely. This would be the start of your plug-in file, popUpForm.jquery.js.

(function($) {
    $.fn.popUpForm = function(options) {

        // Defaults and options
        var defaults = {
            container   : '',
            modal       : true,
            resizeable  : false,
            width       : 440,
            title       : 'Website Form',
            beforeOpen  : function(container) {},
            onSuccess   : function(container) {},
            onError     : function(container) {}
        };
        var opts = $.extend({}, defaults, options);

        self.each(function() {

            // The REAL WORK happens here.
            // Within the scope of this function 'this' refers to a single
            // DOM element within the jQuery collection (not a jQuery obj)
        });
    }
})(jQuery);

The code is wrapped in a self-executing function, and adds itself to jQuery using the $.fn namespace. The identifier following $.fn is the method name you’ll use to invoke it.

We’re also following good coding practices by passing in the jQuery variable explicitly. This will keep us from getting into trouble if the plug-in is used on a page with other JavaScript frameworks, some of which use $ as a variable.

Next, an array of default values is created, and these defaults will be used if they aren’t defined when the plug-in is called. The line immediately following the defaults array merges the passed in options with the defaults and stores them all in the opts array.

Finally, a loop is created for iterating over the jQuery collection identified by the selector when the plug-in is called.. While chances are in most situations it will be a single item ( an anchor), it will still handle multiple links with a single call – assuming they all load the same form.

An important thing to understand is that the value of the special variable ‘this’ changes when we enter the self.each loop; it’s a special jQuery method designed to make looping DOM collections easier. The callback function uses the context of the current DOM element, so the variable ‘this’ refers to that element within the loop.

You can see in a very simple example how ‘this’ refers to a jQuery collection of jQuery objects in the plug-in function scope, but inside the each loop, ‘this’ refers to a single, non-jQuery DOM element.

The Scope of This

Step 5: Starting the Guts

The code for the next few sections is all contained within the self.each block of our skeleton. What do we do now? For each jQuery element passed in, there are going to be several steps to take:

  • Make sure it is a link, and that it goes somewhere
  • Fetch the part of the remote page specified
  • Attach the remote form to the page, and create a hidden dialog for it
  • Steal the link so it creates our pop-up
  • Handle form submissions AJAX style

Before doing any of that, however, we’re going to add one line of code inside the callback, at the very top

var $this = $(this);

This is more then just convenience; the variable ‘this’ will go out of scope in any closures within the each loop, and we’re going to need access to the current object later. Since we’ll almost always want it as a jQuery object, we’re storing it as one.


Step 6: Make Sure the Element Is Valid

$.popUpForm is only going to operate on anchor tags, and the anchor tag must have a href value so we know where to fetch the form from. If either of those conditions is not met, we’re going to leave the element alone. The second line of our ‘guts’ will be:

if (!$this.is('a') || $this.attr('href') == '') { return ; }

Some people hate multiple return points in a function, but I’ve always found having one at the start can make a function more readable, as opposed to using an if(condition) to wrap the rest of the function. Performance wise, they’re identical.


Step 7: Fetch the From From the Remote Page

The $.load method has nice functionality that allows a call to specify and ID in order to only attach part of a fetched document. The script won’t attach the returned HTML directly to the DOM, because $.load only overwrites, it doesn’t append.

var SRC = $this.attr('href') + ' ' + opts.container;
var formDOM = $("<div />").load(SRC, function() {

The variable opts.container has the ID of the form element on the remote page. The second line loads this remote page, and attaches the form and its contents to a div, the entirety of which is stored in the variable formDOM. Notice that $.load includes a callback (the function) — we’ll use formDOM inside that callback.


Step 8: Attach the HTML and Create the Dialog

Inside the $.load callback, the code is going to attach the form, override the click event of the anchor, and override the submit event of the form.

The form’s HTML is stored in the formDOM variable at this point, and attaching it to the existing page is easy.

$('#popUpHide').append(formDOM);

The id #popUpHide refers to a hidden div that will attached to the page by the plug-in. In order to provide that div, the following line will be added at the top of the plug-in. If it already exists, we don’t recreate it.

$("#popUpHide").length || $('<div id="popUpHide" />').appendTo('body').css('display','none');

Now that the form is hidden safely away on our page, it is time to use a call to the $.dialog method to create the form. Most of the set-up params are taken from our plug-in. The ‘autoopen’ option is hard coded since we want the dialog to open when the link is clicked, and not when the dialog is created.

// Create and store the dialog
$(opts.container).dialog({
    autoOpen    : false,
    width       : opts.width,
    modal       : opts.modal,
    resizable   : opts.resizeable,
    title       : opts.title
});

Step 9: Override Default Event Handling

If we stopped here, the plug-in wouldn’t be doing much. The link would still take us to the next page. The behavior we desire is for the link to open the dialog.

$this.bind('click', function(e) {
    e.preventDefault();
    opts.beforeOpen.call($this[0], opts.container);
    $(opts.container).dialog('open');
});

The first line of this click handler is very important. It stops the link from loading the new page when it is clicked.

The second line is our ‘beforeOpen’ callback. The variable opts.beforeOpen contains a function reference – that much is obvious. The .call method is used to invoke the function in a way where we can provide context — the ‘this’ variable for that function. The first argument passed becomes ‘this’ to the called function.

When a function has access to the variable ‘this’ there are some contracts JavaScript has with the programmer that we should maintain.

  • The ‘this’ variable should be the object the function acts on
  • The ‘this’ variable is a single DOM object

In order to maintain that contract, we pass $this[0] instead of $this. $this[0] represents a single, non-jQuery DOM object.

To help understand this a little better, imagine the following callback function:

opts.beforeOpen = function(container) {

    // Gives the value of the link you just clicked
    alert('The remote page is ' + this.href);

    // Gives the id container assigned to this link
    alert('And the container is ' + container);
}

The link click isn’t the only default behavior to override. We also want the form to submit via AJAX, so the normal form onsumbit event needs to be prevented and new behavior coded.

$(opts.container).bind('submit', function(e) {
    e.preventDefault();
    ajaxSubmit();
});

Again, we use preventDefault() to stop the event, and in this case add a new function to handle the form submission. The ajaxSubmit() code could go directly in the callback, but it has been moved to a new function for readability.


Step 10: Handle Form Submissions, AJAX-Style

This function would be added immediately after the end of the self.each loop ( don’t worry, you’ll see the entire plug-in code in one shot in just a bit ). It takes the form, submits it to a remote script, and fires the appropriate callbacks.

The first step is to get the form as a jQuery object, and to determine the form’s method, either GET or POST.

function ajaxSubmit() {
    var form    = $(opts.container);
    var method  = form.attr('method') || 'GET';

If you remember, we stored the form’s ID in opts.container. The next line checks the form for a method, and assigns ‘GET’ if no method is present. This is consistent with HTML which uses GET by default on forms if no method is specified.

Use the $.ajax method to submit the form:

$.ajax({
    type    : method,
    url     : form.attr('action'),
    data    : form.serialize(),
    success : function() {
        $(opts.container).dialog('close');
        opts.onSuccess.call($this[0], opts.container);
    },
    error   : function() {
        $(opts.container).dialog('close');
        opts.onError.call($this[0], opts.container);
    }
});

The URL option is determined from the action attribute of the form tag. The data is produced by using the serialize method on the jQuery object containing the form.

The success and error options are $.ajax callbacks, which we’re in turn using to call our callbacks, in the same way the beforeOpen callback was invoked.

We’re also closing the dialog in for both the success and error handlers.


Step 11: The Entire Plug-In

As a review, let’s look at the code we’ve written so far as a whole, including some helpful code comments:

(function($) {
    var alog = window.console ? console.log : alert;

    $.fn.popUpForm = function(options) {
        // REQUIRE a container
        if(!options.container) { alert('Container Option Required'); return; }

        // Give us someplace to attach forms
        $("#popUpHide").length || $('<div id="popUpHide" />').appendTo('body').css('display','none');

        // Defaults and options
        var defaults = {
            container   : '',
            modal       : true,
            resizeable  : false,
            width       : 440,
            title       : 'Website Form',
            beforeOpen  : function(container) {},
            onSuccess   : function(container) {},
            onError     : function(container) {}
        };
        var opts = $.extend({}, defaults, options);

        // The "this" within the each loop refers to the single DOM item
        // of the jQuery collection we are currently operating on
        this.each(function() {
            /* We want to keep the value 'this' available to the $.load
             * callback */
            var $this = $(this);

            /* we only want to process an item if it's a link and
             * has an href value
             */

            if (!$this.is('a') || $this.attr('href') == '') { return ; }

            /* For a $.load() function, the param is the url followed by
             * the ID selector for the section of the page to grab
             */
            var SRC = $this.attr('href') + ' ' + opts.container;

            /* the event binding is done in the call back in case the
             * form fails to load, or the user clicks the link before
             * the modal is ready
             */
            var formDOM = $("<div />").load(SRC, function() {
                // Append to the page
                $('#popUpHide').append(formDOM);

                // Create and store the dialog
                $(opts.container).dialog({
                    autoOpen    : false,
                    width       : opts.width,
                    modal       : opts.modal,
                    resizable   : opts.resizeable,
                    title       : opts.title
                });

                /* stops the normal form submission; had to come after
                 * creating the dialog otherwise the form doesn't exist
                 * yet to put an event handler to
                 */
                $(opts.container).bind("submit", function(e) {
                    e.preventDefault();
                    ajaxSubmit($this[0]);
                });

                // create a binding for the link passed to the plug-in
                $this.bind("click", function(e) {
                    e.preventDefault();
                    opts.beforeOpen.call($this[0], opts.container);
                    $(opts.container).dialog('open');
                });
            });

        });

        function ajaxSubmit(anchorObj) {
            console.log(anchorObj);
            var form    = $(opts.container);
            var method  = form.attr('method') || 'GET';

            $.ajax({
                type    : method,
                url     : form.attr('action'),
                data    : form.serialize(),
                success : function() {
                    $(opts.container).dialog('close');
                    opts.onSuccess.call(anchorObj, opts.container);
                },
                error   : function() {
                    opts.onError.call(anchorObj, opts.container);
                }
            });
        }
    }
})(jQuery);

This code should all be saved in a file called popUpForm.jquery.js


Step 12: Setting Up the Plug-In

The first step in plug-in usage would be to include all the required dependencies on your HTML page. Personally I prefer to use the Google CDN. The files being on a separate domain can help page load speed, and the servers are fast. Also, it increases the chances that a visitor will already have these files cached.

In the HEAD of the HTML document, add the following:

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/black-tie/jquery-ui.css" type="text/css" />
<link rel="stylesheet" href="css/main.css" type="text/css" />

<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js'></script>

The main.css file is for our site specific styles, everything else is from Google’s CDN. Notice you can even use jQuery-UI themes from the CDN in this fashion.


Step 13: Invoking the Plug-In

Remember, we only want to invoke the plug-in on links that go to a form page. In the online demo, the forms are contained in form.html, and only two links go to that page.

<script>
$(document).ready(function() {
    $('.contact a').popUpForm({
        container   : '#modalform',
        onSuccess   : function() { alert('Thanks for your submission!'); },
        onError     : function() { alert('Sorry there was an error submitting your form.'); }
    });

    $('.survey a').popUpForm({ 'container' : '#othercontainer' });
});
</script>

The calls are wrapped in a document.ready block so we can be sure the anchor elements exist before trying to act upon them. The second call, $(‘.survey a’) is an example of the minimum amount needed to use our new plug-in. The first example sets a callback for both onSuccess and onError.


Step 14: Styling the Modal

If you’ve gotten this far, and you created examples forms and a page to call them from, you’d notice the form in the modal is probably, well, ugly. The modal itself isn’t bad, because we’re using a jQuery-UI theme. But the form inside the modal is mostly unstyled, so we should make some efforts to pretty it up.

The Unstyled Form

There are some things to keep in mind when creating styles for use in a jQuery-UI modal:

  • The modal itself is only a child of the page’s BODY element
  • The contents of the modal are all children of a div of class ‘ui-dialog’

Using these small bits of information we can begin applying styles to the form in the modal. First we give the modal a background color we’re happy with, and also modify the font for the title bar.

.ui-dialog {
        background: rgb(237,237,237);
        font: 11px verdana, arial, sans-serif;
}
.ui-dialog .ui-dialog-titlebar  {
        font: small-caps bold 24px Georgia, Times, serif;
}

Next, we want to separate each item in the form with lines. Since the form structure alternates h3s with divs containing form elements, we add the following rules:

.ui-dialog h3,
.ui-dialog div {
        border-top:1px solid rgb(247,247,247);
        border-bottom:1px solid rgb(212,212,212);
        padding:8px 0 12px 10px;
}

And we only want lines between the sections, not at the very top or very bottom.

.ui-dialog .puForm div:last-child {
    border-bottom:none;
}
.ui-dialog .puForm h3:first-child {
    border-top:none;
}

Lets not forget to style the h3s, and the form elements. The radio buttons need to display inline so they are all in a row.

.ui-dialog h3 {
        font: 18px Georgia, Times, serif;
        margin: 0;
}
.ui-dialog select,
.ui-dialog textarea,
.ui-dialog input {
        width:76%;
        display: block;
}
.ui-dialog #rating input,
.ui-dialog #rating label {
        display: inline;
        width:auto;
}

Remember, these styles are specific to this project, you’ll have to style your own forms depending on what structure you use. To target the form elements specifically, you can either target descendants of .ui-dialog, or to style each form individually, include styles descending from the form ID you’ve included.

The styled form:

The Styled Form

Step 15: Conclusion

So what have we really done? We’ve taken a normal link leading to a contact form (or forms) and caused that form to load up in a modal dialog, and submit via ajax. For users without javascript, nothing happens and the links behave normally, so we haven’t stopped anyone from filling out your forms.

If you click on the survey link in the demo, be sure to submit something. I’ll post the results in the comments for fun after a week or so!

August 30 2010

16:06

Building a Sleek AJAX Email Signup Form


In this tutorial, we’ll learn how to create a slick email signup form. This form will harness the full power of AJAX, meaning that we will submit data to the server, validate it, and receive a response – all without a single page refresh! Along the way, you should pick up some useful tips related to PHP and JavaScript, as well as general programming best practices.



Step 1: The Plan

So, we want to create an email signup form, but not just any signup form: we want to create a super-responsive, AJAX-powered email signup form. This means no pesky page refreshes, giving the end user real-time status updates, and all the juicy goodness of server side data validation. Here is a flow chart of exactly how we want this to work:

Flow Chart Of Events

To accomplish all this hocus pocus, we’ll need to use some pretty cool web technologies. These include JavaScript (with a little lot of help from jQuery), AJAX, PHP, MySQL and JSON. Heres a rundown of what we will be using each technology for:

  • JavaScript – Submit data to the server and parse messages received from the server. We will be using jQuery to handle our AJAX calls and parse our JSON.
  • PHP – Process the data sent to the server. This will include validating the data (making sure it’s OK to put in the database) and handling the response to send back to the browser.
  • MySQL – Store the signup data.
  • JSON – Glue all of the above together. I will explain more about JSON later in this tutorial.

So we know how we want it to work, and we know what technologies we want to use: it’s time to get started!


Step 2: Setting Up the MySQL Database

Ok, first things first: we need to set up our database. At the moment the only data we want to record is the user’s email address, and the date and time he or she signed up. Open up PHPMyAdmin (or whatever program you use to manage your MySQL database) and create a new table in your database using the following statement:

CREATE TABLE `signups` (
  `signups_id` int(10) NOT NULL AUTO_INCREMENT,
  `signup_email_address` varchar(250) DEFAULT NULL,
  `signup_date` date DEFAULT NULL,
  `signup_time` time DEFAULT NULL,
  PRIMARY KEY (`signups_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

The above should be sufficient for what we need. signups_id is an auto incrementing field to assign a unique id to each record, signup_email_address is a varchar field and will be the email address the user uses to sign up with, and signup_date and signup_time are date and time fields which will record when the user signed up. Next, we need to set up the HTML.


Step 3: Setting up the HTML

<form id="newsletter-signup" action="?action=signup" method="post">
    <fieldset>
        <label for="signup-email">Sign up for email offers, news & events:</label>
        <input type="text" name="signup-email" id="signup-email" />
        <input type="submit" id="signup-button" value="Sign Me Up!" />
        <p id="signup-response"></p>
    </fieldset>
</form>

This should be the bare minimum HTML that we need to get this working (I have not included the body tags or header stuff in this snippet just to save space. Do note that you will need to have jQuery loaded on your page). All we need is a text input, a submit button, and a message placeholder. Obviously, you need a label for the input, and I have used a fieldset as I am working with an XHTML strict doctype. The placeholder is where our status message to the user is going to be shown. At the moment it should just be empty.

Unstyled Form

So here’s our form in all its glory. Looks pretty plain, doesn’t it? I’m going to do some CSS for our form to make it look a little less windows95-ish.

* {
    padding:0;
    margin:0;
}

body {
    font-size:12px;
    font-family:Arial, Helvetica, sans-serif;
}

fieldset {
    border:none;
}

form {
    width:930px;
    margin:20% auto;
    padding:15px;
    border:solid 6px #9FCBFF;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
}

input {
    border:none;
    background-color:none;
}

#signup-email {
    border:1px solid #999999;
    color:#9E9E9E;
    padding:5px;
    margin-left:10px;
    margin-right:4px;
}

#signup-email:focus {
    border-color:#9FCBFF;
    background-color:#DFEEFF;
    background-image:none;
    color:#000;
}

#signup-button {
    background-color:#9FCBFF;
    color:#FFF;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px;
    padding:5px;
    text-shadow: 1px 1px 1px #5FA8FF;
}

#signup-button:hover {
    cursor:pointer;
    background-color:#7FB9FF;
}

#signup-response {
    display:inline;
    margin-left:4px;
    padding-left:20px;
}

.response-waiting {
    background:url("loading.gif") no-repeat;
}

.response-success {
   background:url("tick.png") no-repeat;
}

.response-error {
   background:url("cross.png") no-repeat;
}
Styled Form

That’s better. Although our response message is not yet visible (as there in no response yet) it will appear next to the “sign me up” button like so:

Form With Message


Step 4: The Glue

Now that the database access and mark-up have been completed, we need to know how we are going to link the two together.

How is the JavaScript going to be able to send and receive messages from a completely different programming language (PHP)? We are going to use something called JSON.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based open standard designed for human-readable data interchange (similar to XML in intent). JSON is often used for serializing and transmitting structured data over a network connection. It is primarily used to transmit data between a server and web application, serving as an alternative to XML. JSON is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for virtually every programming language. Yep, that includes PHP. Here is a snippet of JSON:

{"hey I'm a key":"and I'm its value!"}

As you can see it’s super-simple. We have encapsulated a key-value pair in some curly braces. The key-value pair relationship is indicated using a colon. The curly braces indicate that this is an object, and everything inside of them is part of that object. You can have multiple key-value pairs in an object:

{"hey I'm a key":"and I'm its value!",
 "hey I'm another key":"and I'm its value!",
 "you guessed it, I'm a key":"and I'm its value!"}

All we have done is split the key-value pairs using a comma. The key-value pairs are actually referred to as members of the object (the JSON object). You can get even more fancy and have an array as a value of a key which holds more objects

{"key1": {
  "key2": "value2",
  "key3": "value3",
  "key4": {
    "value4": [
      {"newobject_1_key_1": "newobject_1_value_1", "newobject_1_key_2": "newobject_1_value_2"},
      {"newobject_2_key_1": "newobject_2_value_1", "newobject_2_key_2": "newobject_2_value_2"},
      {"newobject_3_key_1": "newobject_3_value_1", "newobject_3_key_2": "newobject_3_value_2"}
     ]
  }
}}

Let’s go through this:

  • Key1′s value is an object.
  • Inside that object there are key-value pairs for key2 and key3.
  • Key4 has an object for its value.
  • Value 4 is an array of 3 more objects, which contain 2 key-value pairs each.

But that’s getting too complicated for our needs.

All we are going to need to do is get the server to send us a JSON response containing two members (key-value pairs): one for the status and one for the message. This will look like so:

{"status":"success","message":"Wahey! You've been signed up!"}

status will indicate whether the signup process was successful or not. message will be the message related to the status. If the status is ‘success’ we want to tell the user they are signed up. If the status is ‘error’, then we want to tell the user what went wrong. So if we’re telling the user what has happened via the message member, why do we need the status member? Well, there are two reasons. The first is that we want to apply a class to the response message holder, so that we display a green tick for success and a red cross for an error. The second reason is there can be only one success message that can be sent back (indicating the user has been signed up), but there are up to four error messages that could be sent back. Error messages will occur in the following cases:

  • The user did not enter an email address.
  • The user entered an invalid email address.
  • The email address the user entered has already been used.
  • There is some kind of technical error and the user can not be validated or added to the database.

This means that we also need to know the exact text responses of each message, in order to assign the correct class to the message holder. This equals one massive headache. What if we wanted to change the message sent back? We would then need to revise the code used to assign the class to the message holder as well. It is so much easier to send back the status.

Don’t worry if you do not understand this JSON malarkey yet; as we work

Premium Members: Download this Video ( Must be logged in)

through the rest of the tutorial, it should start to piece together.


Step 5: Preparing It All

Normally, when you submit a form, the browser is redirected to the action of the form. We don’t want this to happen, as we want to submit data in the form using AJAX. The first thing we need to do is stop the form from redirecting us when the submit button is clicked.

$(document).ready(function(){
   $('#newsletter-signup').submit(function(){

        //do our ajax stuff here

        //prevent form from submitting
        return false;
    })
})

Here, we are saying, “when document is ready and the submit event is triggered for any element with an id of newsletter-signup (which just happens to be our form), execute the code inside the function.” This is where we will be inserting the AJAX call, the JSON response handler, and anything else needed to make our form function the way we wish. The only code in this function at the moment is return false. This will stop the form from submitting, which in turn stops it from redirecting us. The next thing we need to do is set up the variables that we are going to be using.

var form = $(this),
    formData = form.serialize(),
    formUrl = form.attr('action'),
    formMethod = form.attr('method'),
    responseMsg = $('#signup-response')

Here we are declaring multiple variables all at once. It just saves writing the var keyword five times. Good times. Anyhow, here is what each variable is for:

  • form – We use the this keyword wrapped in the jQuery object. this refers to the actual form element. We want to wrap it in the jQuery object so we can use other jQuery DOM functions.
  • formdata – We are using the jQuery serialize() function to get all the form data. In its simplest form serialize() gets all the form fields and all their values and puts them in key-value pairs inside a string. We will then send this string of data to the server.
  • formUrl – This is the URL we want to send our data to.
  • formMethod – This is the method we want to use to send our data.
  • responseMsg – This is the element that we are going to use to display our message to the user.

We get the form URL and form method this way so we don’t have to change the JavaScript if we decide to change where and how we send the data to the server in the HTML. We store the response message element in a variable so we only have to search the DOM for it once. To continuously query the DOM for an element is wasteful.

As we are going to be using AJAX to submit the form, we should provide the end user an indication that we are doing some work behind the scenes, so to speak. To do so, we will set the response message holders text to ‘Please Wait…’ and give it a class of ‘response-waiting’. This will give it a cool loading gif :) .

//show response message - waiting
responseMsg.hide()
           .addClass('response-waiting')
           .text('Please Wait...')
           .fadeIn(200);

We hide the response message holder first so that when we set the text, it does not show straight away. Next, we add the class ‘response-waiting’. After that, we set the text to ‘Please Wait…’ and finally fade it in. All we are doing here is chaining together jQuery functions. The responseMsg code could be wrote on one line; I’ve just split it up to make it easier to read.

responseMsg.hide().addClass('response-waiting').text('Please Wait...').fadeIn(200);


Step 6: Submitting To The Server

Okay, it’s time to get to the juicy bit. Now that we have our data, and have provided some visual feedback to the visitor, we’ll use a jQuery function to submit the data to the server.

$(document).ready(function(){
    $('#newsletter-signup').submit(function(){

        //setup variables
        var form = $(this),
        formData = form.serialize(),
        formUrl = form.attr('action'),
        formMethod = form.attr('method'),
        responseMsg = $('#signup-response')

        //show response message - waiting
        responseMsg.hide()
                   .addClass('response-waiting')
                   .text('Please Wait...')
                   .fadeIn(200);

        //send data to server
        $.ajax({
            url: formUrl,
            type: formMethod,
            data: formData,
            success:function(data){
                //do something when ajax call is complete
            }
        })

        //prevent form from submitting
        return false;
    })
})

The magic happens here:

$.ajax({
    url: formUrl,
    type: formMethod,
    data: formData,
    success:function(data){
        //do something we ajax call is complete
    }
})

We are using the jQuery function $.ajax() to submit the data to the server. This function handles all the complicated cross browser XML HTTP Request stuff that we’re not really interested in. Notice something here? Looks a lot like a JSON object…

We need to pass some information to the $.ajax() function so it knows what to do and how to do it. You can pass multiple parameters to the $.ajax() function, but for the sake of this tutorial, we only need to pass it the url, type, data and success parameters.

  • url – This is the url we want to send our data to. We saved this in a variable called formURL earlier.
  • type – This is the method we want use to send our data to the server. We saved this in a variable called formMethod earlier.
  • data – This is the data we want to send to the server. We saved this in a variable called code>formDataearlier
  • success - This is a callback function. It is called if the AJAX call is successful. In this function we will process the JSON response we get from the server.


Step 7: The Success Function

Once we have submitted the data to the server, it will send us a response message back. The message will be a well formatted JSON string. Luckily for us, jQuery has a neat function to parse JSON.

success:function(data){

    //setup variables
    var responseData = jQuery.parseJSON(data),
        klass = '';
}

The argument data that is passed to the success function is our JSON response returned from the server. Within this function, the first thing we want to do is setup two variables:

  • responseData - This will hold the parsed JSON response. The $.parseJSON() function will turn our JSON response into a JavaScript object.
  • klass - This will be a variable that we will set later. It will contain the name of the class we want to apply to the response message holder, based on the response we receive from the server. If you are wondering why we are calling the class variable klass, it is because the word 'class' is a reserved word in JavaScript and can not be used as a variable name.

The next thing must do is determine which CSS class we should apply to the response message holder. The class will be based on what status the server returns. If the status is 'success,' we want to give it a class of 'response-success,' and if the status is 'error,' we'll give it a class of 'response-error'

//response conditional
switch(responseData.status){
    case 'error':
        klass = 'response-error';
    break;
    case 'success':
        klass = 'response-success';
    break;
}

The CSS classes that will be applied to the status messages will look like:

Response Classes

The first one is the loading message (.response-loading), the second is the success message (.response-success) and the third is the error message (.response-error).

We are using a switch statement to determine which class to use based on the status. I could have used if statements, but this is a better way of doing it. The condition we want to compare against is responseData.status. responseData is an object and status is a property of that object. This object was created by the $.parseJSON() function and is based on our JSON response. This response will return two members: status and message. These will be converted into properties of the responseData object. In this switch, we have two cases to compare responseData.status against. If responseData.status is equal to the string 'error', then the klass variable will be set to 'response-error'. If responseData.status is equal to the string 'success' , then the klass variable will be set to 'response-success'. Now all that is left to do is actually show the message to the user.

//show reponse message
responseMsg.fadeOut(200,function(){
    $(this).removeClass('response-waiting')
           .addClass(klass)
           .text(responseData.message)
           .fadeIn(200,function(){
               //set timeout to hide response message
               setTimeout(function(){
                   responseMsg.fadeOut(200,function(){
                       $(this).removeClass(klass);
                   });
               },3000)
            })
})

The first task we do is fade out the response message holder, as it is currently set to 'Please Wait...'. Once this has been completed, we remove the class 'response-waiting', add either the 'error' or 'success' class, set the text to be the message sent back from the server, and then finally fade it back in. All of this is done from the callback of the fadeOut() function. Once the message has faded in, we don't want it to stick around forever so we set a timeout to fade the message out again after three seconds. This is all done from the callback of the fadeIn() function.

As you can see, we are making good use of jQuery's callback functions. These ensure that everything is executed in the correct order, at the correct time. If we did not use the callback functions, we would end up in a situation where we fade the message in and immediately tell it the fade out even though it has not finished fading in. Finally, when the response message holder has faded out we want to remove any classes we assigned to it. That's it for the success function!

And that's it for the JavaScript, too. We have set up our variables, set our status message, submitted the data via AJAX, got a JSON response, parsed the JSON, and returned the status of the submission back to the user. Your completed JavaScript code should look like so:

$(document).ready(function(){
    $('#newsletter-signup').submit(function(){

        //setup variables
        var form = $(this),
        formData = form.serialize(),
        formUrl = form.attr('action'),
        formMethod = form.attr('method'),
        responseMsg = $('#signup-response');

        //show response message - waiting
        responseMsg.hide()
                   .addClass('response-waiting')
                   .text('Please Wait...')
                   .fadeIn(200);

        //send data to server for validation
        $.ajax({
            url: formUrl,
            type: formMethod,
            data: formData,
            success:function(data){

                //setup variables
                var responseData = jQuery.parseJSON(data),
                    klass = '';

                //response conditional
                switch(responseData.status){
                    case 'error':
                        klass = 'response-error';
                    break;
                    case 'success':
                        klass = 'response-success';
                    break;
                }

                //show reponse message
                responseMsg.fadeOut(200,function(){
                    $(this).removeClass('response-waiting')
                           .addClass(klass)
                           .text(responseData.message)
                           .fadeIn(200,function(){
                               //set timeout to hide response message
                               setTimeout(function(){
                                   responseMsg.fadeOut(200,function(){
                                       $(this).removeClass(klass);
                                   });
                               },3000);
                            });
                 });
              }
        });

        //prevent form from submitting
        return false;
    });
});


Step 8: Server Side Validation

Now that we have the HTML prepared, and the JavaScript ready to send and receive data, we need to write our server side code to process the data it's given, and send a JSON response back to the JavaScript. For this tutorial, PHP will be our server-side language of choice.

if($_GET['action'] == 'signup'){
    mysql_connect('localhost','YOUR DB USERNAME','YOUR DB PASSWORD');
    mysql_select_db('YOUR DATABASE THAT CONTAINS THE SIGNUPS TABLE');
    $email = mysql_real_escape_string($_POST['signup-email']);

    //do some stuff

    exit;
}

Here we are saying that if, in the querystring, (as we are using the $_GET array) the parameter action is equal to 'signup,' then execute this code. This is a good way to encapsulate our AJAX call. Firstly we define our MySQL connection using PHP's built in mysql_connect() function. To get this connected to our database we need to give it the host, the database user username, and the database user password. We don't have to do any error checking here, as we are going to do that later in the script. Next, we select the database we want to access using mysql_select_db().

Now that we have got our database access code set up, we can use the mysql_real_escape_string() function to sanitize the data we are sending to the server. This makes the data safe for inserting into the database by escaping certain characters that are classed as unsafe. Because we are posting the data to the server, we use the $_POST array to access our email address. $_POST['signup-email'] will get our email address and we will store it in a variable called $email. The last line of code is the exit statement. This will stop the rest of the script from executing. This is useful if we had lots of code in here, as we only want to run the bit we need and ignore the rest. This is important to keep our AJAX calls nice and speedy. The next thing we are going to need to do is validate the data to make sure that we are not inserting any old junk into the database.

//validate email address - check if input was empty
if(empty($email)){
    $status = 'error';
    $message = 'You did not enter an email address!';
}
else if(!preg_match($emailRegex, $email)){ //validate email address - check if is a valid email address
    $status = 'error';
    $message = 'You have entered an invalid email address!';
}
else {
    $existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
    if(mysql_num_rows($existingSignup) < 1){

        //database insert code

    }
    else {
        $status = 'error';
        $message = 'This email address has already been registered!';
    }
}

We only need to do three checks on our data:

  1. Make sure the user actually submitted an email address
  2. Make sure the email address submitted is a valid email address
  3. Make sure the email address submitted has not already been used to sign up

We are using a series of if statements to achieve this. The first if uses the PHP function empty() to check if the $email variable actually contains anything. If the variable is equal to an empty string, 0, '0', false or null, it will return true (meaning that we have an empty variable). If we have an empty variable, we set a variable called $status to 'error' and a variable called $message to 'You did not enter an email address!'. If our variable is not empty we can proceed to check that it is a valid email address. To do so, we use a PHP function called preg_match(). We give this function a regular expression (the long string full of weird characters) and our email address. If the email address matches the regular expression, the function returns 1 (which equates to true). If it does not match, it returns 0 (which equates to false). In our case if preg_match() returns false, we know the email address is invalid; so we set our $status variable to equal 'error' and our $message variable to equal 'You have entered an invalid email address!'. Otherwise if preg_match() returns true, we can move on to the next check which requires us querying the database to see if our email address has already been signed up. We can use the PHP function mysql_query(), which accepts a SQL query, queries the database, and returns a resource. We do not need to know anything about the data that mysql_query() returns; we only need to know how many records is returned. If it returns more than 0, this email address has been used to sign up before so we set our $status and $message variables accordingly. If no records are returned, we are good to insert our data into the database.

We use the PHP function mysql_num_rows() to find out how many records the query returned. All we need to do is pass it the resource which we saved in a variable called $existingSignup and it will return a number. We then use an if statement to check that the number is less than 1.


Step 9: Insert Into Database

We have verified our data is OK to be put in the database, so we are going to use the following code to so:

$date = date('Y-m-d');
$time = date('H:i:s');

$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
if($insertSignup){
    $status = 'success';
    $message = 'you have been signed up!';
}
else {
    $status = 'error';
    $message = 'Oops, there's been a technical error! You have not been signed up.';
}

The date and time variables are PHP functions that return the date and time in a specified format. Because we set the signup_date field in the database to be a date field and the signup_time field to be a time field, I am formatting my date and time to suit them. The next thing to do is insert the data into the database. This, again, is done by using the mysql_query() function and passing it an SQL statement. Because this is an INSERT SQL statement, the function will return true on success and false on failure. It will not return a resource as there is no resource to return because we were just executing a statement. We then check if the query was successful or not. If it was, we set our $status variable to 'success' and our $message variable to 'you have been signed up!'. Otherwise, if the query failed, we set $status to 'error' and $message to 'Oops, There's been a technical error! You have not been signed up.' We don't need to tell the user what the error was, just that there's been a problem and they have not been signed up. This will also catch any error caused by the initial connection code (like could not connect to database or could not find table, etc).


Step 10: Send The Response Back

The previous step defined two variables: $status and $message. This is the data we want to encode as JSON to send back to the user. We are going to put these two variables into an associative array, so we can provide meaningful names to the keys of the JSON members.

$data = array(
    'status' => $status,
    'message' => $message
);

You don't have to write your associative array like this; though I personally find it easier to read. All we need to do now is pass this array to a PHP function called json_encode(). This turns our associative array into a well formatted JSON string. Once it has been encoded as JSON, we need to return it back to the clients browser. We do this with a simple echo statement.

echo json_encode($data);

And that's it. That's all the server side code needed. You should have ended up with this:

if($_GET['action'] == 'signup'){
    mysql_connect('localhost','YOUR DB USERNAME','YOUR DB PASSWORD');
    mysql_select_db('YOUR DATABASE THAT CONTAINS THE SIGNUPS TABLE');

    //sanitize data
    $email = mysql_real_escape_string($_POST['signup-email']);

    //validate email address - check if input was empty
    if(empty($email)){
        $status = "error";
        $message = "You did not enter an email address!";
    }
    else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
        $status = "error";
        $message = "You have entered an invalid email address!";
    }
    else {
       $existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
       if(mysql_num_rows($existingSignup) < 1){

           $date = date('Y-m-d');
           $time = date('H:i:s');

           $insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
           if($insertSignup){
               $status = "success";
               $message = "You have been signed up!";
           }
           else {
               $status = "error";
               $message = "Ooops, Theres been a technical error!";
           }
        }
        else {
            $status = "error";
            $message = "This email address has already been registered!";
        }
    }

    //return json response
    $data = array(
        'status' => $status,
        'message' => $message
    );

    echo json_encode($data);

    exit;
}

That is all the code we need for the email signup form to work. Hopefully, if you followed this tutorial step by step you, should be recording email signups now. Although our code works and our form does what it should, there is one last thing that will improve the form.

If the user clicks the submit button more than once before the AJAX call has finished, we are going to get some pretty weird results. The message results holder will fade in and fade out again, but the timeout won't reset. This will look daft, as well as causing unnecessary calls to the server. Really, we should stop the user from submitting the form whilst a submission is currently in progress.


Step 11: Stopping Multiple Form Submissions

Stopping multiple form submissions is actually pretty easy to accomplish. All we need to do is check what the form's status is when it is submitted. If it is currently submitting, we don't want to re-submit the form until it has finished. To do this, we'll store the status of the form, on the form, using jQuery's data() function. This function lets us store and retrieve arbitrary data associated with the matched element in key value format. We will use a key called 'formstatus' and its value will either be 'submitting' or 'idle'. If 'formstatus' equals 'submitting,' the form will not be submitted. If it equals 'idle', it will submit. Once the form is submitted, we will need to set 'formstatus' to 'submitting'. And, when ithas finished submitting, we set 'formstatus' to 'idle'. Here's our final JavaScript.

$(document).ready(function(){
    $('#newsletter-signup').submit(function(){

    //check the form is not currently submitting
    if($(this).data('formstatus') !== 'submitting'){

         //setup variables
         var form = $(this),
         formData = form.serialize(),
         formUrl = form.attr('action'),
         formMethod = form.attr('method'),
         responseMsg = $('#signup-response');

         //add status data to form
         form.data('formstatus','submitting');

         //show response message - waiting
         responseMsg.hide()
                    .addClass('response-waiting')
                    .text('Please Wait...')
                    .fadeIn(200);

         //send data to server for validation
         $.ajax({
             url: formUrl,
             type: formMethod,
             data: formData,
             success:function(data){

                //setup variables
                var responseData = jQuery.parseJSON(data),
                    klass = '';

                //response conditional
                switch(responseData.status){
                    case 'error':
                        klass = 'response-error';
                    break;
                    case 'success':
                        klass = 'response-success';
                    break;
                }

                //show reponse message
                responseMsg.fadeOut(200,function(){
                   $(this).removeClass('response-waiting')
                          .addClass(klass)
                          .text(responseData.message)
                          .fadeIn(200,function(){
                              //set timeout to hide response message
                              setTimeout(function(){
                                  responseMsg.fadeOut(200,function(){
                                      $(this).removeClass(klass);
                                      form.data('formstatus','idle');
                                  });
                               },3000)
                           });
                });
           }
      });
    }

    //prevent form from submitting
    return false;

    });
})


Conclusion

Hopefully, you can apply the techniques you've learned in this tutorial to create more complex projects in the future. Thanks for reading, and, if you have any questions or comments, don't hesitate to leave a comment below.

Styled Form

August 16 2010

21:00

How to connect your site with twitter using @Anywhere

Twitter has launched @anywhere, a more simple way of integrating twitter in your site. With it you can add follow buttons, hovercards, linkify twitter usernames and connect with twitter.  In this tutorial, I will show you how to use @anywhere in your site. I will add some twitter @anywhere features to the application build in my previous tutorials, the distance finder (part1 of the tutorial, part2).

What are we going to build?

The distance finder we created using the previous tutorials uses the google maps api to let you find the distance and route between two locations. In this tutorial, I’ll show you how to share your search results with your twitter followers. I’ll also show you how to add hovercards and linkify usernames.

You can view the demo here. And also download the source code.

Prerequisites

The first thing we need to do in order to use @anywhere is to registered a new twitter application. We can do this here. Once we fill in that form, we will be given an APIkey to use in the app.

Next, we’ll have to include the @anywhere script. We’ll add the following code to your <head>section:


<script src="http://platform.twitter.com/anywhere.js?id=ADD_YOUR_API_KEY_HERE&v=1"></script>

Don’t forget to fill in the api key!

As some of the options from @anywhere require jquery, we will have to include that too:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"  type="text/javascript"></script>


Adding a comment box

Let’s see what we need to add to show a small comment box to help us share the search results with our friends.

We’ll have to add another div to the layout, where to show the comment box with the text to share with our friends.


<center><div style="width:100%; height:13%"></div></center>

In the javascript function that shows the route (called continueShowRoute) we will have to add some code to show the comment box.

//we have to create a div where @anywhere will place the comment box; the div will be created inside the share div
var twitter = "<div class='comments'></div>";
document.getElementById("share").innerHTML = twitter;
// we’ll call the share_twitter function with the two addresses as parameters.
share_twitter(address1, address2);

The share_twitter function is used to create the link to share with our friends and show the comment box.

The code which uses @anywhere to show the comment box is pretty simple. It looks like this:

twttr.anywhere(function(twitter) {
   twitter(".comments").tweetBox({
      label: 'Share with your twitter friends!',
      defaultContent: 'My search on distancefinder: '+url,
      height: 30
   });
});

It calls the anywhere function for the twttr object and passes the tweetBox function as a parameter.  The comment box will be shown in the div with the id given as parameter (“.comments”). We can set the following options for the comment box:

  • Label: the text to be shown above the box
  • DefaultContent: the content of the box
  • Height, width: the boxes dimensions
  • Counter: whether or not to show the counter for remaining characters
  • OnTweet: a function to be called when the tweet button is pressed.

We will also have to share the link to the current page. We’ll also have to add the two address values to the url to be able to share a search result. This way, when the friend clicks on our link, they will be redirected to the application page with the addresses set and see our results. We will use PHP Get to pass the two addresses.

As the url might get too long for a tweet, we’ll have to shorten it. For this we can use tinyurl to obtain a shorter url address. To do this, we have to make a request to:


<a href="http://tinyurl.com/api-create.php?url=THE_LONG_URL">http://tinyurl.com/api-create.php?url=THE_LONG_URL</a>

We’ll make a php script that receives an url address, sends a request to tinyurl.com and returns the result.  We’ll store it in the file called getShortURL.php. The script looks like this:

<?php
$url = $_GET['url'];
echo file_get_contents("http://tinyurl.com/api-create.php?url=" . urlencode($url));
?>

We’ll have to call this script using ajax from our share_twitter function and, when we get the result from the script, show the comment box from @Anywhere.

Here’s how the code for this looks like:

var xmlhttp;
function share_twitter(a1, a2)
{
  var my_url = location.href;
  if (my_url.indexOf('?a1=') != -1)
  {
    my_url = my_url.substr(0, my_url.indexOf("?"));
  }
  my_url += "?a1="+a1+"&a2="+a2;

  xmlhttp=GetXmlHttpObject();
  if (xmlhttp==null)
  {
    alert ("Browser does not support HTTP Request");
    return;
  }
  var url="getShortURL.php";
  url=url+"?url="+encodeURIComponent(my_url);

  xmlhttp.onreadystatechange=stateChanged;
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
}

function stateChanged()
{
  if (xmlhttp.readyState==4)
  {
    twttr.anywhere(function(twitter) {
      twitter(".comments").tweetBox({
         label: 'Share with your twitter friends!',
         defaultContent: 'My search on distancefinder: '+xmlhttp.responseText,
         height: 30
      });
    });
  }
}

Here’s what the share_twitter function does. It first get the url of the current page:

var my_url = location.href;

If there are already some variables set in PHP GET it erases them and adds the new values (a1 and a2, the functions parameters)

if (my_url.indexOf('?a1=') != -1)
{
  my_url = my_url.substr(0, my_url.indexOf("?"));
}
my_url += "?a1="+a1+"&a2="+a2;

The rest of the code is a bit more complicated (also, I’ve not shown here the GetXmlHttpObject function; you can see it in the source code), but you don’t have to worry if you don’t get it! All you need to do is that it is used to make the request to the getShortURL.php script and receive the result. When it gets the result (if (xmlhttp.readyState==4)) it calls the @anywhere code to show the comment box and sets the url value to the short url it received.

We will also have to add a few lines of code to our app, to be able to load our friends search results. As I said, we have sent the a1 and a2 parameters (the two addresses) through GET. We will have to add a script to check if the variables are set and if they are, to show the correct map.

We will add this php code before the </body> tag:

<?php
if (isset($_GET['a1']) && isset($_GET['a2']))
{
   echo "<script>start('".$_GET['a1']."', '".$_GET['a2']."');</script>";
}
?>

As you can see, the script will call the start function if the two parameters are set. Let’s see how the start function looks like:

function start(a1, a2)
{
   document.getElementById("address1").value = a1;
   document.getElementById("address2").value = a2;
   initialize();
}

All it has to do is set the address values in the textboxes and to call to initialize() function, the one that shows the map.

And that’s it! We now have a comment box in our app. Of course, the users will have to be logged in their twitter accounts and allow your app to connect to their accounts. But all this is taken care of by @anywhere!

Let’s check out other features of @anywhere:

Linkifying twitter usernames

With only a few javascript lines added to the head section of your site, @anywhere will convert all twitter usernames on your page in links to the proper twitter profiles.

Here’s the script we need to add:

twttr.anywhere(function (T) {
   T.linkifyUsers();
});

You just have to call the linkifyUsers() function. This code will turn all twitter usernames found in the <body> section to links. You can also chose to only linkify the usernames in a section of your site. To do this, you will only need to specify the id of the element which has the usernames you want linkified.

twttr.anywhere(function (T) {
   T("#ELEMENT_ID").linkifyUsers();
});

Hovercards

Hovercards are small tooltips that show some data about a particular Twitter user. These will show up if you go with the mouse over a twitter username on you site. To add this option, you will have to add this script:

twttr.anywhere(function (T) {
   T.hovercards();
});

You can also limit the scope when the hovercards appear, just like with linkifying usenames.

Let’s add a twitter username to the site and test these features:

<center><div style="width:100%; height:4%">Demo App by @anirib</div></center>

@anywhere seems pretty cool, eh?

August 07 2010

10:00

30+ Killer Web Development Screencasts to fine tune your skills

A single image helps us to understand the concept better than a description of 1000 words. In a similar manner reading a code of thousand lines wont make us learn a software than a single video demonstration. There comes the purpose of Screen shots which helps us in the form of screen casts to learn our task in a quick and  relaxed manner. So sit back and do your task in an effective manner.Updating the information on the site or developing the site as a whole is Web Development. Targeting the specific users , a website is developed by planning, analyzing, designing and implementing the same. Then comes the promotion of the site which plays a major role and after promoting, thinking of novel ways to sustain in the industry.

A screen cast gives you a much clear idea by its interactive way of explaining as similar to a live version with the help of a clear audio as in the case of Microsoft Office or Photoshop tutorials. These Screen casts on jQuery, AJAX, PHP and CSS takes you to a tour from the scratch to a level of professional growth.

AJAX:

1.AJAX refreshing RSS content

Overcome the hassles of page refreshing by updating the contents without a manual page refresh. This video demonstrates the do’s and how’s to refresh the RSS feeds with the help of AJAX.

If you’re doing just one feed, I think it’d be more efficient to roll your own JavaScript code, especially if it’s just parsing RSS. From what I remember, SimplePie seemed to be a lot of overhead.

2.Simple-Jquery-spy-effect

The great thing about Realmac’s QuickSnapper site is that if JavaScript is turned off, the list of snaps is visible by default. So we’ll follow suit.

It’s also worth noting that their version only keep pulling in new items until it hits the end. I’ll show you how you can keep the list looping, and in a follow up tutorial I’ll show you how to hook this in to an Ajax hit that doesn’t hammer your server and keeps the effect nice and smooth.

3.Top 25 AJAX video tutorials from youtube

The tutorials presented here gives a beginning from the scratch of how to create a HTML document, adding javascript and also linking an external javascript to that to that,building AJAX chat, adding AJAX elements to a web page using Spy framework,inserting AJAX objects into Adobe Dreamweaver, how to create Mash up applications using AJAX framework,create a Delphi for PHP web  also about AJAX MySql database

Jquery:

4.Sliding headers like iphone

Ever Got frustrated when you cannot find the header while browsing a content and got lost with your subject
when moving on to next page, this screen cast helps the header to remain content and also replaces the next heading simultaneously when you move to next page in a subtle manner.It’s very useful for every web designers who is following the trend.

5.Slidedown animation jump revisited

You would have noticed that your animation jumps towards the end, which could be because of height problems.This screen cast helps you to find a solution by considering the height factors by storing an inline height and setting an an inline height later and proceed accordingly whether we are revealing or hiding the element.We can use this action to show our results or can use this in FAQ’s also.So there’s no need to refresh the page.

6.Slider gallery

Wanna create a gallery with a slide to navigate the items? This screen cast helps you with simple steps to translate the sliders position to slide the products inversely with the help of Markup, slider-widget control, jQueryUI, CSS and certain plug-ins which provides faster scroll and a pause when needed.Using this slider you can display your products and you can roll your images etc.

7.Jquery for absolute beginners

A 15 day Absolute beginner series in Jquery with Theme forest.net as a reference by Jeff Way who has exclusive videos for each day where you could learn all the methods, Jquery style switcher, hover effect and lots more used in Themeforest.net.

This screen cast  series will teach you Jquery clearly and effectively.Each screencasts has the own style and it would be very useful for beginners who needs to learn Jquery in an defective manner.

8.Build Lava lamp style navigation menu

Learn to create a lava-lamp style menu from the beginning which initially demonstrates the same process by using a three level menu and then create a lava-lamp menu by using a Javascript library in this screen cast.

It’s highly professional way to monetize your website and this type of menu will give you a good look to your website.

9.Automatic infinite carousel

Most of the times a scroll action doesn’t stop automatically and we have to control it manually when needed, So to make a scrolling action automatic and pause it when the mouse is over the carousel using Jquery is demonstrated in this screen cast.

We can use this carousel for dynamic purpose too.

10.Jquery look tim van damme

The key effects of Tim the Accordion and Hover effect which work only in Webkit can also work in jQuery when two factors namely animated margin – left and Background rgba crossfade effect is taken into account.

For further details go through the screencast and find it on your own.

11.Popup login window

An authentication is always done with the help of a password.This screen cast will be very useful for authorization purposes.

In this screen cast we create a simple pop up window which verifies the password of an account in an LDAP server and where data is passes from a link to the dynamically created window.

12.Screencasts to build your own jquery plugin

Take the guidance of experts James Padolsey, Jeffery Way and Dan Wellman in this screen cast to create your Jquery plugins and use them in your programs. Lear how to set defaults,pre-load images, create call back methods and create dynamic radio buttons using Jquery, CSS.

To learn the full steps study the complete screen cast.

13.Jquery video series

A more elaborate and precise training regimen of 10 minutes for Themeforest.net and using the same how to use the Jquery library and create your our own projects with the help of video series description for 15 days.

The whole series will bring the beginners as a successful professional in Jquery.They can edit and customize the Jquery applications flexibly.

PHP screencasts:

14.Diving in to PHP

A short tour on various topics in PHP are given as separate tutorials.These self contained tutorials by Jeffery Way teaches you to upload files using PHP with the help of ThemeForest blog which is a complete source on PHP queries.

This screen cast covers the different type of topics for the beginners and intermediate level users.

15.PHP Json Jquery Ajax screencast

To create a communication between PHP and JSON data source using jQuery’s AJAX functionality where we create a script to send the JSON data, then a PHP array  then we load the file and our data source is populated.

To learn the full steps please view the complete screen cast.It’s an advanced screencast for PHP lovers.

16.Photo admin site using PHP and Jquery

This screencast helps you to create a photo site using PHP and jquery where a database is created with collection of photos, and the admin is given the rights of updating the title of the photos as well as maintaining any sub-directories by clicking on the text.

You can administrate the whole photo gallery as per your requirement.The specialty of this screen cast is using Jquery we are accessing the galleries.

CSS screencasts:

17.HTML and CSS the very basics

Help the absolute beginner with the basics of HTML and CSS which are only text files to a level where you can use them as a preview in your website.

This screen cast teach you that HTML is the content and CSS is the design of the website and also how to create a website with good quality.Here you can learn the very basics of both HTML and CSS so you can handle the websites easily when learned the basics well.

18.Editable CSS3 image gallery

We build a pretty typical image gallery design pattern, a grid of images that pop up larger when clicked.This image gallery will give you a highly professional look for your web development.

But this image gallery page makes use of hot semantic HTML5 markup, loads of visual treats with CSS3 and jQuery, and made editable through the CMS PageLime.

19.How to use CSS sprites

CSS Sprites have been a hot topic for a long time now. The fact is that each image on a web page is a separate server request and you can dramatically increase the performance of a page.Reducing the number of HTTP requests improves the load times. To achieve this we use CSS sprites, How to create a CSS sprite and how to those sprites describe here.

This will give you an good idea about CSS sprites and how to use this with your web development side.

20.Detailed look at 960 CSS framework

The 960 Grid System is an effort to streamline web development workflow by providing commonly used dimensions, based on a width of 960 pixels. There are two variants: 12 and 16 columns, which can be used separately or in tandem.

You don’t have to master the code to create a web application .CSS frameworks are there for you to write your code.Spend some time with this screen cast to learn about the frameworks and to efficiently develop your web applications.

21.Image switcher

Image Switcher is a free JavaScript that automatically inserts a series of images into one single hot-swappable view port.This is a pure CSS image switcher that is lightweight and standards-compliant. It could be used for a gallery or any similar function. Any number of list selection options can be used so long as the width can accommodate them.

To change the images as you move across a link is what this screen cast teaches you without the help of JavaScript.You need only z-index switching on hover and a bit of absolute positioning to achieve this.

22.Building a photo gallery

Like many people out there, you may want to create a web site to show off your photos of friends, family, vacation, wedding, etc. Well, this small tutorial will show you how to create a photo gallery and upload it to the Internet.

A photo gallery which automatically builds itself with the images from a directory as well as the sub-directories is possible by CSS . Chris Coyier teaches in this screen cast to build an automatic photo gallery.

23.Embedding audio

How do you embed an MP3 file (like a podcast, song or background music) into a web page or an RSS feed so that visitors can listen to the audio in the browser itself without requiring an external player like QuickTime or Windows Media Player.

Most of the image we either use an image or an audio file. But an image with an audio in the background makes a user quite comfortable to grasp the information. Chris Coyier teaches the same with the help of JavaScript and Flash in this screen cast.

24.Using CSS3

Many exciting new functions and features are being thought up for CSS3. We will try and showcase some of them on this web page.For visual enhancements such as multiple backgrounds, RGB, border image, border radius, @font face, animations / transitions and a lot more for CSS3 is on the move now.

To follow this latest wave catch a glimpse of this screen cast.

25.Introducing firebug

You can get the information about the markup, CSS, layout and DOM of an element in a page with Firebug, an extension of Firefox which has become inevitable for Web designers and developers where you can edit and see the results directly in the browser.

To know more learn this screen cast.

26.Unique page for twitter updates

When designed right, a Twitter feed can improve the aesthetics of a website’s layout.If tweeting is your pastime then you must be eager to display your tweets from start to finish. For e.g. you could cover the design in Photoshop also style your page.

To achieve this task follow this screen cast which guides you from the javascript stuff to CSS to style your page.

Codeigniter:

27.Basic screencasts

Code Igniter is an open source web application for writing PHP programs and also to create full -features web applications.writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries.

In this screencast it gives you introduction about CodeIgniter and also to create a blog in CodeIgniter using PHP by Derek Jones.

28.Easy development with codeigniter

With raw PHP, this can be somewhat time-consuming. However, with CodeIgniter, it’s simply a matter of referencing the correct library, and passing in some configuration options! Let’s dive in.

Eager to tune PHP skills after learning the introduction , Move on to the next step ,this screencast teaches you to upload an image and save it after initial validation using PHP in CodeIgniter.

29.Killer startup screencasts for codeigniter

Get ready to create your first application with CodeIgniter, create a form using Form builder, build a sample application,create a blog in 20 minutes, create a Pagination, send and receive data via jQuery Post and JSON in this 10 minute screencast by Derek Jones.

We are hoping that you will learn further on CodeIgniter Application Development Framework after watch out screencast.

XML:

30.Build a login and registration system with xml

Building an entire membership system can be a tedious, and time-consuming task. Tim Cooper is going to show us how to build the ENTIRE thing in roughly thirty minutes.

Using XML we could create a login and registration form in much less time than MySQL, Tim Cooper in this screen cast shows us this by reviewing PHP, .htaccess, files, sessions and more.

31.Form builder

It may seem odd to attempt to standardize data types in a system DESIGNED TO BE SO FLEXIBLE, but more than one institution reports that setting reasonable expectations for portfolio deployments across campus and managing your IT resources to leverage some amount of standardization do a lot to the project sustainable.

Learn the basics of building a form using the Form builder tool which could be used to build an XML schema file and also use for many multiple purposes in many forms. Sean Keesler teaches you to build a form in this screen cast.

32.Parametrize test data using XML

Create automation scripts to test web application functionality in Internet Explorer on Windows.

From this Screen cast achieve this task with the help of Pamie – a Python class file which creates a Pamie test script to automate a form, create an XML file, read data and run the test.

It show you:

  • How to create a Pamie test script to Automate a form
  • How to find the names and ID’s of DOM Elements to automate
  • Creating an XML file from scratch using Notepad++
  • How to read the data in an XML file using ElementTree
  • How to run the test

33.Screen casts to get you kicking ass with drupal

Find it difficult to learn Drupal, this screencast makes it easy for practically learning step by step process starting with the installation, node system, block system, content types, theme development and more.

Also you could find resources for Drupal books, Drupal podcasts, Drupal forums, Drupal channels.

34.Drupal roundup

Get all the information you wanted to know about Drupal, this screencast gives you the best of Drupal’s screencasts, best books on Drupal, resources, modules and also the annoyances of Drupal. Get the latest screencasts on Drupal 6, Learn about CSS Injector, Node Convert, open buffet syndrome, creating a backup, about Webform, Login Toboggan, Input filters, Teaser length and lots more about this content management platform – Drupal.

July 20 2010

12:20

50 Useful JavaScript and jQuery Techniques and Plugins

Advertisement in 50 Useful JavaScript and jQuery Techniques and Plugins
 in 50 Useful JavaScript and jQuery Techniques and Plugins  in 50 Useful JavaScript and jQuery Techniques and Plugins  in 50 Useful JavaScript and jQuery Techniques and Plugins

We are regulalry collecting useful JavaScript and jQuery snippets, libraries, articles, tools and resources and present them in compact round-ups here, on Noupe. This time we are again covering some useful JavaScript and jQuery techniques, plugins and tools that may help you improve the user experience for your site.

Useful JavaScript and jQuery Techniques

Colorful Sliders With jQuery & CSS3
In this tutorial we are using jQuery and the new transformation features brought by CSS3 to create a three dimensional dynamic slider effect. The techniques presented here – for creating sliders, and CSS dynamic resizable bars, can be used together or in part for powering all sorts of jQuery goodness.

JS-03 in 50 Useful JavaScript and jQuery Techniques and Plugins

Sponsor Flip Wall With jQuery & CSS
Designing and coding a sponsors page is part of the developer’s life (at least the lucky developer’s life, if it is about a personal site of theirs). It, however, follows different rules than those for the other pages of the site. You have to find a way to fit a lot of information and organize it clearly, so that the emphasis is put on your sponsors, and not on other elements of your design.

JS-39 in 50 Useful JavaScript and jQuery Techniques and Plugins

TipTip jQuery Plugin
TipTip detects the edges of the browser window and will make sure the tooltip stays within the current window size. As a result the tooltip will adjust itself to be displayed above, below, to the left or to the right of the element with TipTip applied to it, depending on what is necessary to stay within the browser window.
TipTip is a very lightweight and intelligent custom tooltip jQuery plugin. It uses ZERO images and is completely customizable via CSS.

JS-00 in 50 Useful JavaScript and jQuery Techniques and Plugins

Nivo Slider
The Most Awesome jQuery Image Slider

JS-02 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery.Syntax
jQuery.Syntax is an extremely fast and lightweight syntax highlighter. It has dynamic loading of syntax source files and integrates cleanly using CSS or modelines.

JS-04 in 50 Useful JavaScript and jQuery Techniques and Plugins

jquery.timepickr.js
This is my humble attempt to enhence web time picking.

JS-05 in 50 Useful JavaScript and jQuery Techniques and Plugins

Photo Zoom Out Effect with jQuery
Today we will show you how to create a simple image zoom out effect with jQuery. The idea is show some images which are zoomed in initially and when hovering over an image it gets zoomed out. This effect could be used in photography websites or image galleries. Our example uses some black and white images to focus on the effect.

JS-06 in 50 Useful JavaScript and jQuery Techniques and Plugins

A Fresh Bottom Slide Out Menu with jQuery
In this tutorial we will create a unique bottom slide out menu. This large menu will contain some title and a description of the menu item. It will slide out from the bottom revealing the description text and some icon. We will use some CSS3 properties for some nice shadow effects and jQuery for the interaction.

JS-07 in 50 Useful JavaScript and jQuery Techniques and Plugins

Making a Mosaic Slideshow With jQuery & CSS
Today we are making a jQuery & CSS mosaic gallery. Mosaic, because it will feature an interesting tile transition effect when moving from one slide to another.

JS-08 in 50 Useful JavaScript and jQuery Techniques and Plugins

17 jQuery Plugins for Easy and Efficient Reordering and Filtering Page Elements
Having full control of elements on a page and the order they are presented in can be quite useful. jQuery as always is a safe choice to go for. There are several good quality plugins to pick from. This post provides an overview of plugins you can use to provide simple yet powerful functionality to reorder, filter, add drag and drop capabilities etc.

JS-09 in 50 Useful JavaScript and jQuery Techniques and Plugins

Create an Impressive Content Editing System with jQuery and PHP
I’m going to show you how to use jQuery and PHP to build a content editing system that will allow you or your client to easily edit .html pages visually.

JS-10 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery MegaMenu Plugin

JS-11 in 50 Useful JavaScript and jQuery Techniques and Plugins

Excellent JQuery Plugins To Enhance Form Validation
Simple jquery plugins can enhance and beautify HTML form elements, these simple jquery scripts turn a simple HTML website to a fantastic look and feel. These plugins can be enabled very easily. In this roundup I have gathered most beautiful Jquery plugins that are related to all kinds of form validation. This list also includes roundups of some blogs. Go ahead and enjoy

gameQuery – a javascript game engine with jQuery
gameQuery is a jQuery plug-in to help make javascript game development easier by adding some simple game-related classes. It’s still in an early stage of development and may change a lot in future versions. The project has a Google Code page where the SVN repository of the project is hosted and a twitter page where you can follow the daily progress of the development.

JS-13 in 50 Useful JavaScript and jQuery Techniques and Plugins

Getting Buggy CSS Selectors to Work Cross-Browser via jQuery
Below I’ve prepared a simple table that describes a number of CSS selectors that are not cross-browser compatible, along with the jQuery syntax for each. The syntaxes are exactly the same as they would be in CSS, save for the jQuery wrapper (just remove $() and the quotes to get the CSS syntax), so using these selectors in jQuery will provide somewhat of a practice ground to prepare you for when they’re fully supported by all commonly-used browsers.

JS-14 in 50 Useful JavaScript and jQuery Techniques and Plugins

jqFancyTransitions: jQuery Image Rotator Plugin
jqFancyTransitions is easy-to-use jQuery plugin for displaying your photos as slideshow with fancy transition effects.

JS-15 in 50 Useful JavaScript and jQuery Techniques and Plugins

A demo of AD Gallery
A highly customizable gallery/showcase plugin for jQuery.

JS-16 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery UI Selectmenu: An ARIA-Accessible Plugin for Styling a Custom HTML Select Element
Our latest contribution to labs is the selectmenu plugin, which is designed to duplicate and extend the functionality of a native HTML select element, and lets you customize the look and feel, add icons, and create hierarchy within the options. Best of all, it’s built with progressive enhancement and accessibility in mind, has all the native mouse and keyboard controls, and is ThemeRoller-ready.

JS-17 in 50 Useful JavaScript and jQuery Techniques and Plugins

Create a Content Rich Tooltip with JSON and jQuery
Today we’re going to break the mold of the traditional tooltip. This tutorial will demonstrate how to build tooltips that are powered by jQuery, with information pulled from a JSON array.

JS-18 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery image zoom effect
So today I’m going to run through the technique used to zoom the image thumbnails and display the overlay of text.

JS-19 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery Roundabout Shapes
Roundabout Shapes provide even more paths along which your Roundabout can move. The current version of Roundabout Shapes offers eleven additional movements.

JS-20 in 50 Useful JavaScript and jQuery Techniques and Plugins

Extending jQuery’s selector capabilities

JS-21 in 50 Useful JavaScript and jQuery Techniques and Plugins

How to show/hide a hidden input form field using jQuery
This past week I was working on a project at work which included building a request form with multiple fields. It was a rather large form that included a dropdown list with an ‘other’ option. I wanted to allow users to select the ‘other’ option which then would show an input field so they can enter a specific description of what that ‘other’ item is. I didn’t want to clutter the form by displaying that additional field by default so I used a little jQuery, thus displaying it dynamically and only when needed.

JS-22 in 50 Useful JavaScript and jQuery Techniques and Plugins

A Better jQuery In-Field Label Plugin
This is a pretty nice effect, and it can really help to save space on forms. There are a billion different ways to implement this, and I don’t suggest you use the example from above because that was just a quick way to show the effect. So let’s walk through a couple of different implementation approaches and figure out the best way to implement this feature.

JS-24 in 50 Useful JavaScript and jQuery Techniques and Plugins

Useful JavaScript / jQuery Tools

JavaScriptMVC
JavaScriptMVC is an open-source framework containing the best ideas in enterprise JavaScript development. It guides you to successfully completed projects by promoting best practices, maintainability, and convention over configuration.

JS-26 in 50 Useful JavaScript and jQuery Techniques and Plugins

PEG.js – Parser Generator for JavaScript
PEG.js is a parser generator for JavaScript based on the parsing expression grammar formalism. It enables you to easily bulid fast parsers which process complex data or computer languages. You can use it as an underlying tool when writing various data processors, transformers, interpreters, or compilers.

JS-27 in 50 Useful JavaScript and jQuery Techniques and Plugins

PhoneGap
PhoneGap is an open source development tool for building fast, easy mobile apps with JavaScript.

JS-28 in 50 Useful JavaScript and jQuery Techniques and Plugins

JavaScript Shell
A command-line interface for JavaScript and DOM.

JS-29 in 50 Useful JavaScript and jQuery Techniques and Plugins

WireIt – a Javascript Wiring Library
WireIt is an open-source javascript library to create web wirable interfaces for dataflow applications, visual programming languages, graphical modeling, or graph editors.

JS-30 in 50 Useful JavaScript and jQuery Techniques and Plugins

JavaScript Programming Patterns
In this article I am trying to present some of the techniques out there that I have discovered. The patterns I would like to mention are the following:
- The Old-School Way
- Singleton
- Module Pattern
- Revealing Module Pattern
- Custom Objects
- Lazy Function Definition

JS-31 in 50 Useful JavaScript and jQuery Techniques and Plugins

Compare JavaScript frameworks
Modern Web sites and Web applications tend to rely quite heavily on client-side JavaScript to provide rich interactivity, particularly through the advent of asynchronous HTTP requests that do not require page refreshes to return data or responses from a server-side script or database system. In this article, you will discover how JavaScript frameworks make it easier and faster to create highly interactive and responsive Web sites and Web applications.

JS-32 in 50 Useful JavaScript and jQuery Techniques and Plugins

How to Test your JavaScript Code with QUnit
QUnit, developed by the jQuery team, is a great framework for unit testing your JavaScript. In this tutorial, I’ll introduce what QUnit specifically is, and why you should care about rigorously testing your code.

JS-33 in 50 Useful JavaScript and jQuery Techniques and Plugins

CoffeeScript
CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript’s less ostentatious kid brother — the same genes, roughly the same height, but a different sense of style. Apart from a handful of bonus goodies, statements in CoffeeScript correspond one-to-one with their equivalent in JavaScript, it’s just another way of saying it.

JS-34 in 50 Useful JavaScript and jQuery Techniques and Plugins

Mind-blowing JavaScript Experiments
The following JavaScript experiments demonstrates the amazing capabilities of the modern browsers such as Chrome and Safari. In this post I will showcase to you an array of experiments that will surely blows your mind off.

JS-35 in 50 Useful JavaScript and jQuery Techniques and Plugins

Online javascript beautifier
This little beautifier will reformat and reindent bookmarklets, ugly javascript, unpack scripts packed by the popular Dean Edward’s packer, as well as deobfuscate scripts processed by javascriptobfuscator.com.

JS-36 in 50 Useful JavaScript and jQuery Techniques and Plugins

CSS & Javascript Character Entity Calculator
Enter your HTML Entity Character number (such as &#2335 or just 2335 – ?) to get the CSS and JS values for that entity.

JS-37 in 50 Useful JavaScript and jQuery Techniques and Plugins

Dygraphs: Create interactive graphs from open source Javascript library
Dygraphs is an open source JavaScript library that produces an interactive, zoom-able charts of the present time series. It is mainly designed to display the dense data sets and enable the users to explore and interpret them. It is a JavaScript Visualization Library.

JS-38 in 50 Useful JavaScript and jQuery Techniques and Plugins

Showdown – Markdown in JavaScript
Showdown – a JavaScript port of Markdown

JS-40 in 50 Useful JavaScript and jQuery Techniques and Plugins

Copy to Clipboard with ZeroClipboard, Flash 10 and jQuery
With today’s post I will show you a contrived example to get you started. I eventually hope to add this to the contextMenu.js jQuery plugin that I use, but for now this should be pretty straight forward. I do want to note that in the demo and download I am loading the latest version of the jQuery library (1.3.1) from Google’s CDN for the first time in any of my posts. For more information on how to do this see the instructions from Google.

JS-41 in 50 Useful JavaScript and jQuery Techniques and Plugins

fLABjs
fLABjs is a special API wrapper around LABjs which adapts the code to work properly in a file:// local filesystem environment. There are a number of things with core LABjs does which are not appropriate for local filesystems, such as XHR, special path handling rules, etc.

JS-43 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery LazyLoad Ad : Delays loading of advertising
jQuery LazyLoad Ad is a jQuery plugin that takes advantage of LazyLoad delaying ads loading.

qTip – The jQuery tooltip plugin
qTip is a tooltip plugin for the jQuery framework. It’s cross-browser, customizable and packed full of features!

JS-47 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery Collapsing and Expanding Table Rows

JS-48 in 50 Useful JavaScript and jQuery Techniques and Plugins

Improving Search Boxes with jQuery
This time we will learn how to improve a little more our sites by adding some additional interactions to our search boxes like autofocus, highlighting, autoreplace default text and more by using jQuery.

JS-49 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery Grid Plugin

JS-50 in 50 Useful JavaScript and jQuery Techniques and Plugins

Pines Notify jQuery Plugin
Pines Notify’s features include:
- Timed hiding with visual effects.
- Sticky (no automatic hiding) notices.
- Optional hide button.
- Supports dynamically updating text, title, icon, type…
- Stacks allow notice sets to stack independently.
- Control stack direction and push to top or bottom.

JS-51 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery Slider plugin (Safari style)
jQuery Slider is easy to use and multifunctional jQuery plugin.

JS-52 in 50 Useful JavaScript and jQuery Techniques and Plugins

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
(PRO)
No Soup for you

Don't be the product, buy the product!

close
YES, I want to SOUP ●UP for ...