Quick Tip: How to Extend Built-in Objects in JavaScript

Quick Tip: How to Extend Built-in Objects in JavaScript

Constructor functions, like Array, offer a wide range of methods and properties that you can make use of. But have ever wished that one of these objects offered some method that isn’t built-in? Is there a way to do so yourself? Absolutely! Let’s see how.

Reversing a String

This little snippet takes advantage of the Array object’s “reverse” method, and applies its functionality to a given string. In effect, something like “hello” will be turned into “olleh,” and can be accessed by using “myString.reverse()”.

String.prototype.reverse = function() {
	return Array.prototype.reverse.apply(this.split('')).join('');
};

var myString = 'hello';
console.log(myString.reverse());

Bonus Question

Now that we have a basic of understanding of augmenting objects, can you figure out a way to write a custom “contains” method for the String object? For example, the jQuery library allows us to write things like:

$("div:contains('John')").css('fontWeight', 'bold');

The snippet above will search through all of the divs on the page, and then filter that wrapped set down to only those that contain the string “John.” How could we extend the String object, with raw JavaScript, to allow for this? Leave your solution in the comments, and we’ll discuss!



24 Best Practices for AJAX Implementations

24 Best Practices for AJAX Implementations

Implementing AJAX technology can be a hit or miss thing. Do it well and you’ll have users raving over the slickness it provides to the general user experience while if you mess it up, you’ll be at the receiving end of their wrath. Here are 24 tips to guide you with implementing AJAX technology within your web application.

1. Understand What it All Means

First up, you need to understand what AJAX is, what it stands for and how it has revolutionized parts of the internet. You’ll need to know what its advantages are before you can make an informed decision

Here is a list of must read articles to get you up to speed.

2. Check for Appropriate Usage Scenarios

AJAX can sound all fine and dandy but there are only so many places you can implement it without it sounding like another bullet point. Do proper research and testing to make sure you are implementing AJAX for the right reasons. Because it sounds nice is not a valid reason.

Proper usage scenarios would be if you have lots of data in the back end and want to update the UI as and when the user needs access to that data or when you want to emulate a proper desktop application and handle everything asynchronously. An extremely bad scenario is when you have each page of a static web site load through AJAX for no reason other than you can. Use your discretion here.

3. Learn to Implement it With Raw Code

Before you delve into writing your code, understand the raw code to do it first. Libraries are great at reducing the time it takes to create browser agnostic code but when it breaks it’d be best if you know how to do it without libraries helping you.

I highly recommend Jeffrey’s tutorials on making AJAX requests with raw JavaScript here and here.

4. Use a Library

Once you’ve mastered the raw JS which handles the AJAX implementations, it’s best you shift over to a JavaScript library which provides robust support for AJAX. Any of the major libraries like jQuery, Prototype or MooTools should do.

Libraries not only provide an exhaustive feature set you can make use of but also makes sure your code is compatible with all browsers without you having to do anything extra.

Here are a few of our favorites which encompass proper AJAX functionality:

5. Master the Library

Once you’ve gotten the hang of making AJAX requests with your library of choice, it’s time to take it to the next level and master it. It may sound a little redundant but there is a big difference between the two.

With each library getting bigger, packing more features with each release, the developers hide a huge amount of functionality from the beginner developer. For example, did you know that there are multiple methods in jQuery to make AJAX calls? Or that a number of event triggered methods are only available with the core AJAX call? A lot of people don’t know that and thus are unable to leverage the untapped potential of the library.

Here are a few choice resources for your perusal:

6. Provide Feedback

Tutorial Image

On of the main reasons people were against AJAX in the past was they couldn’t really tell when the application updates the data it contains. This is also an integral part of the general user experience made even more pertinent with AJAX.

So even for the tiniest thing, remember to provide feedback to the user letting them know their action has been registered. The user has clicked on a button? Let them know!

7. Utilize Proper Events and Callback Functions

Whether you are using raw JS or a library to implement this functionality, you’ll have access to the state of the request i.e. whether the request was successful; met with an error and finally whether it has been completed.

Make proper use of these events and their respective callbacks to manipulate the UI for a better user experience. For example, if the request was unsuccessful, you’d want to update the user interface to reflect that their changes weren’t successful while if it was successful, you’d want to tell them so. Don’t keep the user waiting!

With jQuery, you’d make use of the success and error callbacks. You also get other callbacks such as complete and beforeSend to be invoked for apporopriate use.

$.ajax({
        //Other code
           success: function(msg)
        {
            // Update the UI here to reflect that the request was successful.
            doSomethingClever();
        },
        error: function(msg)
        {
            // Update the UI here to reflect that the request was unsuccessful
            doSomethingMoreClever();
        },
        complete: function(msg)
        {
            // Update the UI here to reflect completion
            doSomethingEvenMoreClever();
        }
});

– Show quoted text –

8. Choose the Right Format for the Job

Just because XML occurs in the abbreviation doesn’t mean you are limited to XML for the payload. You are free to choose whatever format strikes your liking. JSON? Sure. XML? Naturally. HTML? Of course. Raw strings? Definitely.

So, essentially, whatever floats your boat. You aren’t limited to any format. You get to choose whichever format makes the work at hand easier for you and makes the most sense for that specific instance.

9. Read Extensively

AJAX, while old in relative terms, is still very much in flux. Exciting new solutions are created everyday while scarily thorough books covering the subject are often released. Be it web developments blogs (like this one!) or books, keep reading to keep yourself informed of the latest developments.

Here are my most visited and/or read blogs and books:

10. Experiment Continuously

Reading book after book and article after article is awesome but to get a grip on the subject, you’ll need to fold up your sleeves and write some code yourselves. Trust me, you’ll learn a lot more a lot quicker reading a bit and then writing some code about it than just reading continuously without writing any code to better understand what you’ve learnt.

11. Utilize Firebug

Tutorial Image

Firebug is arguable the most important tool in every web developer’s repertoire. Along with impressive JavaScript debugging and other potent features, it also let’s you see each AJAX request as it is made along with a myriad other details about the request including from where it originates, what its payload is and so much more. You can download it right here.

Here are a few more recommended resources:

12. Keep the Users With Old Browsers in Mind

Unless your web application is like Google Maps it’s always a good idea to provide users with a fallback so they can still use your application. Case in point would be the numerous web applications which route all their user interactions through AJAX if they have the capability while falling back to a normal HTML version otherwise.

13. Bookmarkability

The tendency to bookmark is a pervasive habit of the average web user and it’s imperative your application respects that. With AJAX, the address bar of the browser is not updated which means when a user wants to bookmark a page with content loaded dynamically with AJAX, he/she is going to bookmark the initial page and not the updated page. This presents a huge problem.

Fortunately, there are a few techniques to fix this problem. Here is a selected list of articles intended to help you with that:

14. Use Proper Animations

This is another of those user experience issues which may mar an otherwise spectacular application. Often with an AJAX application, the user may fail to even notice a change has occurred with an element of the user interface or the data it contains. In light of this issue, it’s essential that the developer uses non-garish, tasteful animations to draw the user’s attention to the fact that the user interface has been updated to reflect the user’s actions.

You can read about how to use jQuery to create tasteful, cross browser animations here.

15. Respect the Back Button

The back button is another action that has become part of a normal web user’s habits. Make sure your application adheres to this respected paradigm to avoid angering users. Trust me, they will, if suddenly their back button doesn’t work as intended.

Here is a list of article which should help you with the matter.

16. Change the DOM Intelligently

Imagine this: your request has succeeded and has returned a chunk of data with which you hope to update your user interface. If this chunk of data has few individual chunks, you can proceed as usual. If instead it has, say, 15 contiguous elements to be updated, it is better to just create the elements, modify their data in memory and replace those in the DOM in one big swoop rather than accessing each element and updating the DOM each time separately.

Modifying the DOM separately leads to worse performance as the number of edits to be made increases.

So, for a chunk of HTML like so:

<div id="container">
<span id="elem1"></span>
<span id="elem2"></span>
</div>

instead of doing this:

$("#elem1").html("Value 1");
$("#elem2").html("Value 2");

Do this:

var updatedText = "<span id=\"elem1\">Value1</span>
<span id=\"elem2\">Value2</span>";
$("#container").html(updatedText);

It might look a lot of work for just two elements but once you extrapolate it to more, the performance alone will be worth it. It’ll be faster since you’ll be updating the DOM just once irrespective of how many elements you have within the updated HTML. With the usual method though, the number of edits required to the DOM scales linearly to the number of elements which in turn degrades performance.

17. Comment Your Code

This is a no-brainer but comment your code properly. Chances are, your code is going to be looked at by a few hundred people , at least, looking to learn from you and commenting is definitely going to earn your extra rep points and paragon cookies.

You don’t necessarily need to comment every tiny bit of your code; commenting just the important bits is sufficient.

This is too much!

$.ajax({
    // Switch off caching
    cache: false,

        //Set the type of request
       type: "GET",

        // Set the timeout
    timeout: 5000,

        // Specify the proper handler
       url: "handler.php",
       success: function(msg)
        {
           // Update the UI here to reflect that the request was successful.
           doSomethingClever();
        },
        error: function(msg)
        {
           // Update the UI here to reflect that the request was unsuccessful
           doSomethingMoreClever();
        }
});

A much better way to add comments since a lot of it is self explanatory.


// Make an AJAX call to handler.php and update the UI
$.ajax({
    cache: false,
       type: "GET",
    timeout: 5000,
       url: "handler.php",
       success: function(msg)
        {
           doSomethingClever();
        },
        error: function(msg)
        {
              doSomethingMoreClever();
        }
});

18. Make an Informed Decision About the Request Type

This is strictly a general web application tip than specifically an AJAX tip but do take special note of the type of request you are making: GET or POST. The XMLHttpRequest object is capable of making both type of requests but it is up to you to decide what kind to make.

As their names signify, a GET request is used to procure data from a source while a POST request is used to submit data to be processed. With an AJAX GET request, as with a normal GET request, you’ll have to pass on the query data as part of the URL itself manually as opposed to a POST request where the data is sent automatically. Also note that GET requests are cached automatically while a POST request isn’t.

19. Use a Proper IDE

Tutorial Image

When it comes to JavaScript, please don’t be an elitist and limit yourself to plain old notepad. Your productivity will spike sharply with the use of a proper IDE, specially one with support for your JavaScript library of choice.

For the PC loyalists

For my fruit flavored brethren

  • Coda
  • Espresso
  • <a
    href=”http://macromates.com/”>TextMate
  • <a
    href=”http://www.aptana.com”>Aptana
  • <a
    href=”http://www.adobe.com/products/dreamweaver/”>DreamWeaver CS4

20. Participate in the Community

Getting to be a part of awesome web development communities, like this, will not only expose you to a wider range of ideas but will also lead you to the path of writing better code. By writing and commenting on articles similar to these, you’ll not only teach people less knowledgeable than you on the subject but you’ll also be able to learn more from the more experienced people who comment on your code.

As Jeff says, you only truly understand something when you’ve taught it to someone else.

21. Tweak Your Response Times

By response time I mean only one thing: the time before a user triggers an AJAX request. Consider this, you are typing in an input box which uses AJAX to retrieve search suggestions from the server. Response time would be the time duration between the key press and the AJAX call being made. Too fast and you’d have to do multiple requests for each letter of the search phrase. Too slow and you’ll have the user twiddling his thumbs wondering as to how he broke the application.

This isn’t limited to just the scenario noted above. This applies to each and every non-definite (click) user action. Test rigorously with your users to find the optimum latency.

22. Use Status Indicators

Tutorial Image

This is an extension of a point noted above but just as important. Users coming from the desktop application or a general web application paradigm will be flummoxed when they use an AJAX enabled web application. While notifying the user when a change has been made is good, you’ll also need to make sure to let them know that a request has been initiated in the first place.

This is where status indicators come in. These are the little rotating or bouncing GIFs you see in applications. In function these are similar to the hour glass cursor used in desktop operating systems.

Here is a wonderful little tool which lets you create an indicator of your choice.

23. Appreciate JSON-P’s Awesomeness

Often, as part of the cross site mashup you’re creating, you’d need to access data from other sites through AJAX requests. This flies directly in the face of the cross domain restriction most browsers enforce. In this case, instead of going with exotic solutions like masking and proxying, you could just use JSON-P.

JSON-P, JSON with Padding, essentially lets us circumvent this restriction and lets us obtain data from third party domains. Here is a list of articles to get you started:

24. Ask Questions Freely

Don’t be shy to ask questions. Every one of us started as a complete newbie and began by asking questions. There are plenty of placed to clarify your doubts including the comments section of Nettuts+. Never, ever be afraid of asking questions. Just try to be a little polite! It always helps.

That’s all folks

And we’re done. Twenty four points to keep in mind when implementing AJAX within your site or web application. Hopefully, this has been useful to you and you found it interesting. I’ll be closely watching the comments section so chime in there if you have any counter arguments or different perspectives on the matter.

Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at [email protected].

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial



Quick Tip: How to Work with @Font-face

Quick Tip: How to Work with @Font-face

Due to the fact that @font-face can be a bit overly complicated, it hasn’t caught on quite as much as it should. Once you start reading about licensing, different font formats, browser consistencies, it can potentially become more trouble than it’s worth.

But – in five minutes, I’ll try to simplify the process of working with custom fonts as much as I possibly can. Services like Font Squirrel help to make the task a cinch!


Final CSS

@font-face {
font-family: 'blok-regular';
src: url('type/Blokletters-Potlood.eot');
src: local('Blokletters Potlood Potlood'),
 local('Blokletters-Potlood'),
 url('type/Blokletters-Potlood.ttf') format('truetype');
}

@font-face {
font-family: 'blok-italic';
src: url('type/Blokletters-Balpen.eot');
src: local('Blokletters Balpen Balpen'),
 local('Blokletters-Balpen'),
 url('type/Blokletters-Balpen.ttf') format('truetype');
}

@font-face {
font-family: 'blok-heavy';
src: url('type/Blokletters-Viltstift.eot');
src: local('Blokletters Viltstift Viltstift'),
 local('Blokletters-Viltstift'),
 url('type/Blokletters-Viltstift.ttf') format('truetype');
}

h1 { font-family: blok-heavy, helvetica, arial; }

Notice how we’re referencing both an .eot and .ttf font? This is because, of course, Internet Explorer only uses its own format, that has yet to truly catch on. As such, we must first import that .eot file, and then move on to the different formats for Firefox, Safari, etc. It’s essential that you load the .eot version first.

Next, we search for the font on the user’s computer by using the “local” attribute. If it’s unfound, only then do we pass a url that will load the font.

Why Doesn’t IE Try to Load the TTF Fonts?

This was definitely a concern. If Explorer can’t work with the truetype format, we don’t want to waste time trying to download the font. Luckily, because of all those local attributes, and the commas, IE won’t understand any of it. As such, it will simply skip the line all together, thus, only utilizing the .eot version.



Why Web Developers Should Switch to Google Chrome

Why Web Developers Should Switch to Google Chrome

Check out Chrome 4’s great new features for developers, such as cross-platform support, awesome web inspector integration, and handy new extensions. It’s becoming more and more difficult to deny Chrome the title as the new browser for web developers. If it’s not quite there yet, it will be soon!

Introduction

With quick load times, a snappy JavaScript engine, solid WebKit foundation, and big-name backing, Google Chrome has been gaining a respectable market share, even surpassing Safari to become the 3rd most popular browser in December. For developers, however, Firefox has been the sweetheart of many due to its ability to run on any operating system and because of its rich offering of web development add-ons, such as Firebug and the Web Developer Toolbar. But it’s important to test JavaScript in all browsers, and having a robust set of tools in each (including Internet Explorer), is precisely what developers need to make the most of their code.

Lucky for us, the Google folks have been working hard to make Chrome cross-platform, integrate WebKit’s fantastic Web Inspector, and add extensions, making Chrome 4 an amazingly useful tool for web development. In this tutorial, I’ll demonstrate some of the features that make Chrome 4 a great addition to the web developer utility belt.

Downloading Chrome 4

As of January 25, Chrome 4 has been officially released as stable for Windows. Mac and Linux users, however, we have to be a bit more brave in order to experience all that Chrome 4 has to offer. Mac users need to download the “dev” version, and Linux users the “beta” version, and it’s highly worth it! Check out the following links to get a copy of Chrome for your operating system that supports everything we’ll discuss in this article:

Web Inspector (aka Developer Tools)

A screenshot of the Profile Panel of the Chrome Developer Tools

Now let’s get into the nitty gritty! In Firefox, Firebug is a godsend for developers, providing a debugging console, HTML & CSS manipulation, JavaScript profiling, and a whole lot of other goodness. The WebKit folks took notice and over the last couple of years have been perfecting a set of tools called the Web Inspector, which offers a similar set of features to Firebug. Within Chrome 4, the Web Inspector is labeled “Developer Tools.”

Accessing the Web Inspector/Developer Tools

A demonstration of how to access the Developer Tools on Google Chrome for Mac

In addition to Chrome 4, the Web Inspector has been in action for a while from within previous versions of Chrome and Safari, although it’s a bit hidden. To access the Web Inspector in various browsers:

Safari 4

  • Select “Edit > Preferences” (Windows) or “Safari > Preferences” (Mac)
  • Select the “Advanced” tab
  • Check “Show Develop Menu in menu bar”
  • A new menu item, “Develop,” will appear
  • Select “Develop > Show Web Inspector”

Chrome 3 (Windows only)

  • Select the Wrench
  • Select Developer
  • Select JavaScript Console (the whole range of tools are hidden under this name)

Chrome 4

  • Windows / Linux: Select the Page Icon > Developer > Developer Tools
  • Mac: Select View > Developer > Developer Tools

JavaScript Console

A screenshot of the Console Panel within the Chrome Developer Tools

If you haven’t worked with the Firebug or Web Inspector console, then you’re missing out on a great way to help debug JavaScript. The JavaScript console serves several important functions, such as capturing errors and presenting them in a useful format, testing short bits of JavaScript, and as a convenient place to log useful information like variable values and execution times. Practically speaking, I use this tool regularly to evaluate the performance of my programs and to ensure that certain variables are being calculated correctly.

Elements Panel

A screenshot of the ELements Panel within the Chrome Developer Tools

In addition to the JavaScript console, it’s always nice to have a tool that allows you to quickly view the HTML and style information of particular elements on the page. The Web Inspector Elements panel gives a tree-structure view of the Document Object Model (DOM), allowing you to drill down into the document to select an item of interest. You can also access the information of a certain object by right clicking on an item within the browser and selecting “Inspect Element.”

Finally, I should note that the Elements panel allows for much more than simple inspection. You can modify and add styles, edit html, and in the latest versions, view event listeners attached to a selected DOM element. These features can all come in very handy when you’re dealing with little quirks that you can’t quite figure out.

Resources

A screenshot of the Resources Panel within the Chrome Developer Tools

The last feature I’d like to highlight within the Web Inspector/Developer Tools is the “Resources” tab. If you’ve worked with Firebug’s “Net” tab, then you’ll notice several similarities. Essentially, the Resources tab gives a breakdown of all the information that is exchanged between your browser and the server, from the images to the JavaScript to the document itself. It also shows a ton of handy information, such as:

  • A graph of the time it takes to download each component
  • A graph showing the size of the various components
  • A way to sort the requests by type, e.g. Documents, Stylesheets, Images, etc.
  • Image previews with dimensions, file size, and MIME type displayed below
  • Request and Response Headers
  • XML HTTP Request (XHR) information

An elegant tool that allows for easy inspection of page speed, the Resources tab can aid you in identifying and squashing performance bottlenecks. Give it a try and see where your page is too fat, then slim down your chunky images and code to provide a better experience for your users!

Further Reading

A complete overview of the Web Inspector/Developer Tools could easily be a tutorial on it’s own, but we have more ground to cover! I highly recommend checking out the following resources to learn more:

Extensions

Now, while I’ve always been blown away by the speed of Safari 4 and Chrome as compared to Firefox, they’ve both lacked a critical feature: add-ons. In Chrome 4, that all changes with the addition of “extensions.” You can add functionality to Chrome by downloading and installing extensions or by using the standard tools of the trade: HTML, CSS, and JavaScript, to write your own. Extensions can be downloaded from the Chrome Extensions Repository, and should be fairly simple to install. Already, a number of very compelling extensions have been created which aid web development, from quick validation to resolution testing. Let’s take a look at a few.
        

Speed Tracer

A screenshot of the Speed Tracer extension

A web developer can never really be obsessed enough with performance, and the more tools that identify sluggish performance the better. That’s just where Speed Tracer, a Chrome extension developed by Google, comes into play. Speed Tracer takes the “Resources” panel to the next level by providing a visualization of the time it takes to execute low-level tasks, such as rendering CSS or parsing HTML and JavaScript. I’d highly recommend taking a look at a video demonstration of Speed Tracer put together by the folks at Google to get a better idea of how it can help you improve the performance of your applications.

Pendule

A screenshot of the Pendule extension

Moving from Firefox to Chrome, one extension everyone is going to look for is a replacement of the fantastic Web Developer Toolbar. For those who don’t know, the Web Developer Toolbar deals with the tasks Firebug wasn’t meant to handle, such as quick validation of HTML and CSS, the ability to quickly disable JavaScript or images, and a tool for checking links. Those functions are all handled with style by Pendule, which offers much of the core functionality of the Web Developer Toolbar (not quite all), while offering a few goodies of it’s own, such as a color picker.

Resolution Test

A screenshot of the Resolution Test extension

Web Developers often need to ensure that their designs work at a variety of resolutions. Resolution Test allows developers to efficiently resize their browser window to a number of common resolutions for quick and easy testing. The latest version even allows you to open multiple windows at different resolutions with only a couple of clicks. Resolution Test is fantastic for making sure your target audience is seeing the page you want them to see.

Webpage ScreenShot

A screenshot of the Webpage ScreenShot extension

There are occasions when its necessary not only to grab a screenshot of the current visible portion of a website, but a screenshot of the whole page. For example, you may want to print a full page for peer critical review or to demonstrate in your portfolio. I formerly used a Desktop tool for this, but now Webpage ScreenShot does a nice job of capturing full-page screenshots in a few clicks.

Chrome Sniffer

A screenshot of the Chrome Sniffer extension

Do you ever stumble upon a fantastic page and wonder, “what are they using to build this?” I do, and often find myself digging through the source code trying to figure out who the man behind the curtain is. While it is a useful training exercise, and a necessary one if you really want to know what’s going on, Chrome Sniffer can usually give you a snapshot of which JavaScript and PHP frameworks are in use for a particular page. For example, navigate to NetTuts and Chrome Sniffer informs us that it’s run on WordPress using Google Analytics and jQuery.

Conclusion

The future of web development continues to look brighter and brighter! While only a few years ago we had a limited set of tools for debugging JavaScript, tinkering with CSS, and viewing HTML, today we have a variety of powerful options. Now that Google Chrome has become cross platform, fully integrated the WebKit Web Inspector, and added extensions, it is a versatile tool for helping developers improve their own pages. I encourage all of you to download a copy for yourself and give it a shot to see if it can help you improve your pages, then come on back here and share your favorite plugins and tools with the rest of us!

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at [email protected].

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial



CodeIgniter from Scratch: Day 8 – AJAX

CodeIgniter from Scratch: Day 8 – AJAX

The CodeIgniter from Scratch series was unexpectedly, and significantly popular. Today, I’m pleased to announce that, with the help of one of my best authors, Burak, we’ll be continuing the series! Additionally, the most often requested topic is the subject for today’s screencast: combining CodeIgniter and jQuery.

Remember, it is not required that you watch the previous lessons in order to understand today’s screencast. It’s a self-contained article. However, if you’re new to CodeIgniter, we do recommend that you start from the beginning!

Catch Up

Day 8: AJAX

Other Viewing Options



JavaScript Events from the Ground Up: New Plus Tutorial

JavaScript Events from the Ground Up: New Plus Tutorial

Almost everything you do in JavaScript is supposed to begin when something happens: the user clicks a button, hovers over a menu, presses a key, you get the idea. It’s pretty simple to do with libraries like jQuery, but do you know how to wire up events in raw JavaScript? In this week’s Plus tutorial and screencast, I’m going to teach you just that! Help give back to Nettuts+ and join our Plus program!

Whether you prefer a written tutorial, or an in depth screencast, we’ve got you covered. Andrew will teach you about the intricacies and inconsistencies of working with multiple browsers and JavaScript events.

Join Tuts Plus

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service called “TUTSPLUS”. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!

  • Subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.



Quick Tip: Different Layouts for Different Widths

Quick Tip: Different Layouts for Different Widths

It’s becoming more and more common for web sites and applications to provide different layouts dependent upon the user’s window size, or resolution. This can be accomplished in a variety of ways, ranging from CSS to JavaScript solutions.

In this video quick tip, we’ll learn how laughably simple it is to do this with a touch of jQuery, and the resize() method.

By utilizing jQuery’s “resize()” method, we can easily listen for when the user changes the width of their browser window.

function checkWindowSize() {

	if ( $(window).width() > 1800 ) {
		$('body').toggleClass('large');
	}
	else {
		$('body').toggleClass('large');
	}

}

$(window).resize(checkWindowSize);

Then, subsequently, we target our desired CSS properties accordingly.

#container {
	width: 800px;
	height: 1000px;
	background: #e3e3e3;
	margin: auto;
}

/* Change container size for larger windows. */
.large #container {
	width: 1000px;
}

#nav {

	width: 100%;
	height: 100px;
	border-bottom: 1px solid white;
	background: #999999;

}

.large #nav {
	float: left;
	width: 200px;
	border-bottom: none;
	border-right: 1px solid white;
	height: 1000px;
}



Top 10 Things that JavaScript Got Wrong

Top 10 Things that JavaScript Got Wrong

JavaScript, if only by default, is one of the most popular programming languages available. Over the years, it’s been labeled as a nightmare to work with, and, to some extent, this is true! However, more often than not, what people mean to say is that the DOM API is a nightmare. Nevertheless, there are a handful of flat-out errors in the language.

I’d like to make a note that I love JavaScript. This article is only meant for some fun, and for us to be aware of some its short-comings.

1. The Name. JavaScript is NOT Java

We’ll start with a fun jab at the name choice. While it was originally called Mocha, and then LiveScript, it was later changed to JavaScript. According to history, its similarities to the name Java was the result of a collaboration between Netscape and Sun, in exchange for Netscape bundling the Java runtime within their popular browser. It’s also been noted that the name came, almost as a joke, due to the rivalry between LiveScript and Java for client-side scripting.

Nevertheless, it resulted in thousands of “JavaScript has nothing to do with Java” comments in forums across the web!

2. Null is an Object?

Consider this…

console.log(typeof null); // object

This makes zero sense. If null is the absence of a value, then how could its type be “object?” The simple answer is that it’s flat-out an error that dates back to the first release of JavaScript – one that was even incorrectly carried over to Microsoft’s JScript.

3. NaN !== NaN

NaN, as we’d expect refers to a value that is not a legal number. The problem is that NaN isn’t equal to anything…including itself.

console.log(NaN === NaN); // false

This is just wrong. Instead, if you want to determine if a value is indeed NaN, you can use the isNaN() function.

4. Global Variables

The dependence upon global variables is widely considered to be far and away the worst part of JavaScript. For simple projects, much like the quick tips on this site, it doesn’t truly make a difference. However, the real burden of globals come into play when you begin referencing multiple scripts, without any knowledge of how they’re created, or named. If they happen to share the same name as one of your variables, your program is going to throw some sort of error.

“The problem with JavaScript isn’t just that it allows them (global variables), it requires them.” – Crockford

5. User-Agent Strings Report Mozilla. Ever Wonder Why?

Alright – this one isn’t the fault of JavaScript. I cheated a bit. It’s because of the browser vendors. Having said that, user-agent string detection is very common in JavaScript; so it’s important to know what you’re dealing with. It probably doesn’t belong in this list, but who cares! It’s good to know.

This one isn’t as much a mistake as it was an unavoidable decision. For example, open Safari, access the Web Inspector, and log the user agent string into the console.

console.log(navigator.userAgent);
// Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-us) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10

Note that first string of characters: Mozilla/5.0. Why would Safari identify it as a Mozilla based browser? Though it later correctly identifies itself, that still doesn’t explain why they’d bother to mislead programmers. In fact, you’ll find that most browsers identify themselves as Mozilla. The answer goes back a decade, and is, again, less an error, and more an unavoidable circumstance.

For those unfamiliar, a user-agent string is simply meant to identify the browser and its version. As an example, the first ever browser, Mosaic, had a user-agent string that looked like so:

Mosaic/0.9     // browser name / version number

This makes perfect sense. And when Netscape came onto the scene, they kept Mosaic’s usage, and also added an encryption type section.

Mozilla/2.02 [en] (Win95; I)     // browser name / version / encryption

So far so good. The problems came into play when – wait for it – Internet Explorer 3 was released. Keep in mind that, when they launched, Netscape was the most popular browser available. In fact, many servers and programs were already implementing user-agent detection in order to identify Netscape. Though this is a highly debated topic today, back then, it wasn’t much of an issue. If IE had used their own user-agent string, it would have looked something like this:

MSIE/3.0 (Win95; U)

This would have left them at a huge disadvantage, because Netscape was already being identified by many servers. As such, the developers decided to incorrectly identify the browser as Mozilla, and then append an additional set of information labeling it as Internet Explorer.

Mozilla/2.0 (compatible; MSIE 3.0; Windows 95)

Nowadays, user-agent detection is a last effort, and its considered so precisely for this reason. You’ll find that most browsers followed IE’s lead in identifying themselves as Mozilla. Think of it as a chain reaction.

Further Reading

I highly recommend that you read Nicholas Zakas’s “History of the User-Agent String,” if you’d like to delve deeper.

6. Scope Inconsistencies

Consider the following code:

// Create a function that will call a function with the name equal to parameter fn.
function foo(fn) {
    if (typeof fn === "function") {
        fn();
    }
}

// Create an object with a property and a method.
var bar = {
    barbar : "Hello, World!",
    method  : function() {
        alert(this.barbar);
    }
};

bar.method(); // Alerts Hello, World!
foo(bar.method); // If we call the foo function add pass the "bar.method" method, it somehow alerts "undefined."
foo(function() { bar.method(); }); // alerts Hello, World, after

The reason why foo(bar.method) does not render the same result is because the method function will be called as a method of the window object, rather than bar. To fix this, we must call bar.method() from within the passed anonymous function.

Thanks so much to Jeremy McPeak for notifying me of this error.

7. The Use of Bitwise Operators

JavaScript shares many similarities with Java – one of them being the set of bitwise operators.

  • &and
  • |or
  • ^xor
  • ~not
  • >>signed right shift
  • ???unsigned right shift
  • <<left shift

Consider the first item, &; it would be much more efficient to use the && operator, as it’s quicker. This is because JavaScript isn’t the same as Java, and doesn’t have integers. As such, a relatively length process is required to convert the operand, do something with it, and then convert it back.

This is why you can get away with using & for “and”, and | for “or” – even though you should be using && and ||.

8. Too Many Falsy/Bottom Values

Maybe this isn’t specifically an error in JavaScript, but it certainly makes the learning process, especially for beginners, a tough one. Values like null, false, and undefined almost mean the same thing, but there are differences that can be confusing to understand.

Falsy Values

To test, open up the console in Firefox, and find the boolean of the following items.

!!(0); // false
!!(false); // false
!!(''); // false
!!(null); // false
!!(undefined); // false
!!(NaN); // false

Please note that any other values will be interpreted as truthy.

More than an error, this many falsy values is just confusing!

9. It Can’t Do Arithmetic

Okay, okay – I’m 99% teasing with the heading above. But JavaScript does have a few minor issues when working with decimals, for example, things like money transactions. For example, open up your console, and log “.2 + .4″. We would expect it to display “.6″, correct? Well it does, and it doesn’t!

Math
console.log(.2 + .4); // 0.6000000000000001

How come? At a high level, it’s because JavaScript used the IEEE Standard for Binary Floating-Point Arithmetic. I, probably like you, don’t fully understand exactly what that specifies, but just know that, when dealing with decimal fractions, results can vary slightly from what you might expect. Keep in mind that integer arithmetic is perfect, so this really isn’t a huge issue.

10. Code Styling Isn’t your Choice!

When it comes to your coding style, it’s exactly that: your style. Some people prefer to place their curly braces on the same line as the control, others prefer that it goes on its own.


 // braces on the right
return {
  foo : bar
};

// braces on their own line
return
{
  foo : bar
};

Dependent upon the first web dev book we read, or how our teacher taught us, it’s perfectly acceptable to use either of the methods above, or even a combination of the two. The problem with JavaScript is that it’s not your choice!

I learned this particular example from a lecture that Doug Crockford gave around a year ago. Consider the return statement from above. Believe it or not, they ARE NOT equal. Don’t believe me? Try this out. Add the following to some HTML page.

var foo = function() {

	return {
		a : 'b'
	};

}();

alert(foo.a); // b

The code above simply creates a variable called foo, which is equal to the returned object. When we alert(foo.a), we, as expected, see an alert box with a value of ‘b.’ Now, simply take that opening curly brace, from the return statement, and push it down to its own line, like so.

return
{
	a : 'b'
};

If you run it in your browser again, you’ll receive a Firebug error, logging that “foo is undefined.” What the hell!? :)

So why does JavaScript do this? It’s because of something called “semicolon insertion.” Essentially, JavaScript will attempt to correct our bad coding. If, for instance, it thinks that you’ve left off a closing semicolon, it’ll go ahead and add it on for you. Though this was originally intended to be a convenience, especially for newer JavaScripters, it’s actually a very bad thing when you don’t have control over your own code, as demonstrated above.

In our example, there’s no way to determine why foo.a returns “undefined. ” Now that we’re aware of semicolon insertion, the reason it’s undefined is because JavaScript will add a semicolon to the end of the return statement.

return; // JS incorrectly adds this semicolon.
{
	a : 'b'; // It'll add a semicolon here as well, because it doesn't realize that this is an object.
};

So, if we immediately return, it has no idea what the property “a” is, thus, resulting in “undefined.”

Conclusion

As I mentioned at the beginning of this article, I love JavaScript and use it daily. But that doesn’t mean that there aren’t some really awful errors in the language. I’d love to hear your thoughts in the comments! Thanks for reading. Retweets and Diggs are always appreciated! Thanks so much to Jeremy McPeak, Doug Crockford, Nicholas Zakas, and John Resig: I referred to your tutorials and books when preparing this article.



What’s Changed in jQuery UI 1.8 – Plus Free Books!

What’s Changed in jQuery UI 1.8 – Plus Free Books!

jQuery UI 1.8 is currently at the release candidate stage and, barring the discovery of a major bug or flaw, will shortly become the current stable release of jQuery’s official UI library. So what has changed since the last current stable release of 1.7.2? One of the major differences of course is that the library now runs on the latest release of jQuery itself – version 1.4.1, but there have been many other changes including the addition of some great new components, which we’ll look at over the course of this article.

Free Copies of jQuery UI 1.7

The author of this article, Dan Wellman, recently released jQuery UI 1.7, from Packt Publishing. It’s a fantastic read, and I’m pleased to announce that we have a handful of copies to randomly give out. Simply leave a comment about the article, and you’ll automatically be entered into the drawing. Check back on Monday to find out if you’re a winner!

jQuery UI 1.7

Bug Zapping

This release of the library brings several bug fixes for some key components including the Datepicker and Dialog widgets and the Droppable, Resizable and Selectable interaction helpers. None of the bugs were show-stoppers, but nevertheless, clearing out the bugs is a critical part of the ongoing progression of the library. One important point to note is that the beforeclose event of the Dialog widget has been deprecated and replaced with beforeClose so that it follows the same naming convention as the events of other components.

As well as bugs in the code, several styling and accessibility issues have also been addressed; notably the title text of Dialog widgets can no longer disappear behind the close icon, and the keyboard navigability of the new button widget has been improved. For a complete list of all bug fixes included with version 1.8 see the changelog at http://jqueryui.com/docs/Changelog/1.8rc1

Positioning

jQuery UI now has a unique positioning system that that can be used whenever a widget needs to be positioned relative to another element, such as with a drop-down menu or a floating tooltip. The Position utility allows us to easily specify, using a series of simple strings, which part of the positioned element should be fixed to which part of the specified target element. So for example, the “top left” point of one element can be fixed to the “bottom right” of another specified element.

The utility also features a robust collision detection system which prevents viewers of the page being exposed to unsightly toolbars if the element being positioned gets too close to the edge of the viewport, or cannot otherwise occupy its positioned place.

The API for this utility is compact, with just 7 configurable options at this stage. This gives us all the control we need however and allows us to specify up to 81 possible combinations of positioning; options we can configure include the following:

at:
Refers to the position on the target element the element being positioned will be fixed to; the method accepts a single string comprised of the value for the horizontal axis (either right, center, or left) followed by the value for the vertical axis (either top, center, or bottom). There is no separating character between the 2 values.
bgiframe:
If the bgiframe plugin is available on the page, this option will apply an iframe shim to the positioned element, which can help to prevent select elements showing above the positioned content in IE6.
collision:
This option determines how collisions are handled; it accepts one of the following strings: flip, fit or none. The default is flip, which causes the element being positioned to invert the position relative to the target element, e.g. “right center” will become “left center”.
my:
Refers to the element being positioned; accepts same values as at.
of:
Accepts a jQuery selector specifying the target element.
offset:
Specify a number of pixels to offset the element being positioned on the target element.
using:
A callback function can be used with this option allowing you to animate the positioning of the element.

Autocomplete

One of my favourite widgets has returned as an official UI component! Autocomplete was a beta widget in an early 1.6 version of the library and is now back after a complete refactor. It is attached to text inputs on the page and supplies a list of possible choices when a visitor begins typing in the text field.

The widget can take its data (the matching items in the suggestion menu) from a variety of sources including a standard JavaScript array, JSON via an AJAX request or a flexible callback function that can implement any data source and return a customized response to display in the suggestion menu.

Autocomplete is a highly configurable widget and features a full API of options, methods and events to make use of. It’s completely themable via SteamRoller and fully keyboard navigable. All in all this component brings a lot of functionality to your pages. At some future point caching may also be a configurable behaviour.

Let’s take a look at its API; it contains the following three configuration options:

delay:
We can specify the number of milliseconds the widget should wait before displaying the suggestion menu when the visitor begins typing in the input.
minLength:
This option takes an integer that refers to how many characters should be typed into the input before the suggestion menu is displayed.
source:
We configure the data source using this option; possible values include an array of strings representing the items to show in the suggestion menu, or an array of objects where each object contains two properties – the first is the label shown in the suggestion menu, the second is the value that will be added to the input if an item in the suggestion menu is selected. We can also supply a single string representing a remote resource that can return the data asynchronously, or a callback function that can request the data and return it to the widget in the required format.

The following two methods are exposed by Autocomplete:

close:
Used to close the suggestion menu.
search:
Perform a search of the available data and display the suggestions if the term is matched. Can take a predefined value as the term which is passed into the method as an argument, or the value of the input field it is associated with.

We can also hook callback functions into the following custom events:

change:
Fired after an item in the suggestion menu is selected and the menu is closed.
close:
Fired whenever the suggestion menu is closed, whether or not an item was selected. Precedes the change event.
focus:
Fired directly before focus is given to an item in the suggestion menu.
open:
Fired once the data has been returned, directly before the suggestion menu is displayed.
search:
Fired directly before the data source is searched. The search can be cancelled by returning false from a callback function bound to this event.
select:
This event is triggered when an item from the menu before the menu closes.

As a special bonus, the source file for the Autocomplete widget also contains the beta Menu widget, which is still currently in development and is due for release in a later version of the library. So far it looks like a robust and attractive addition to the library, and allows us to transform an unordered list into an attractive drop-down or fly-out menu. Many features are supported including sub-menus, icons, dividers and even a drill-down menu with breadcrumb.

Button

The button widget allows us to implement attractive and functional buttons that can be configured to behave like a particular type of button; for example, we can crate standard push buttons, radio-style buttons where only a single button in a set may be selected, or check-style buttons where any number in a particular set may be selected. Several types of button that incorporate a simple drop-down menu can also be created.

It’s a very flexible widget and can be built using a variety of underlying elements including <button>, <input> and <a>. The buttons are fully accessible and ARIA compliant, adding or removing the appropriate roles and states when necessary. The API is relatively simple at this point, but covers all essentials with three configurable options and a single method to invoke; the configuration options are as follows:

icons:
This option allows us to specify primary and secondary icons to display on the button. It expects an object with the keys primary and secondary, and CSS class names as the values.
label:
With this option we can set the text that is displayed on the button; a string value is expected, but if this is not supplied the value of the underlying HTML element from which the button is created can be used.
text:
The text option accepts a Boolean indicating whether or not to show a text label on the button, which could be the case if a simple icon is all that is needed. The default value is true.

The event that we can bind to in order to execute a callback function and react to interaction is the click event; the native click event of the browser is used unless with the radio or checkbox-style buttons, in which case the event is fired by the widget, not the underlying element.

Mouse Utility

The final new utility to be found in jQuery UI 1.8 is the Mouse utility, which is used by other library components in order to better distribute related implementations of the same behaviour by different widgets. This is great for developers because it means that if mouse interaction is a required behaviour of a custom UI widget, the logic in this utility can be used without having to rewrite it manually. Like the Menu component however, this utility should be considered beta and subject to considerable revision in future releases.

The API is very compact; there are just three configurable options; there are a series of private methods that are used internally by the plugin, but nothing we would need to manually invoke. The configurable options are as follows:

cancel:
This option accepts a string value containing selectors and allows us to configure elements that interaction should be cancelled on. The default value is ‘:input, option’ so for example, in a drag and drop implementation, these elements would not be draggable.
distance:
This option accepts an integer representing the number of pixels the mouse should move before the interaction is registered. The default is 1.
delay:
This option also accepts an integer, but this time refers to the number of milliseconds that should elapse before the interaction is registered. The default of this option is 0.

Summary

jQuery UI 1.8 is shaping up to be a fine release of the library; with a combination of both bug-fixes and new components it’s looking like an important milestone in the library’s roadmap. We first looked at the library’s new positioning system which gives us easy access to a huge number of different was of positioning one element relative to another element. We then looked at the two new components Autocomplete and Button and saw the different configuration options, methods and events exposed by each of their APIs.



Working with RESTful Services in CodeIgniter

Working with RESTful Services in CodeIgniter

CodeIgniter is becoming well known for its power as a PHP based web application framework, but it’s not often that we see examples of it being used for anything else. Today we’ll learn how we can use CodeIgniter to create a RESTful API for your existing web applications, and demonstrate how to interact with your own API or other RESTful web-services, such as Facebook and Twitter.

Tutorial Details

Introduction

If you have been following the CodeIgniter From Scratch series you will know by now that it is relatively quick and easy to put together simple web applications, such as blogs, CMS systems, brochure sites, etc. One thing you may not have thought about is using CodeIgniter to create an interactive API. After trying several existing REST implementations, I found they not only lacked simplicity but were missing most of the features you would expect from a RESTful implementation; so I built my own. This tutorial will show you how to use this code to set up your REST API, and gives example of how to interact with it from your web application.

Assumptions

  1. You have a web server set up, locally or online and known how to manage files on it.
  2. You have read a few of the CodeIgniter from Scratch tutorials.
  3. You know how to set up CodeIgniter.
  4. You know a little about RESTful services.

This tutorial is broken down into two parts. We will start by learning how to create a RESTful service, then further down, we will learn how to interact with it in a few different ways.

Part 1 – Creating a RESTful API

Step 1: Setting up the Demo

Firstly you need to download the codeigniter-restserver code from GitHub and extract it and move the code to your server.

When you open the folder, you will see an entire CodeIgniter install, which is there to power the demo. This allows people to have a play with the REST demo before integrating with your existing application.

Open up “application/config/config.php” and set the base_url to get links working. This base_url will be different for everyone and depends entirely on where you uploaded your files.

Step 2: The URLs

With the files extracted and the base_url set, we are ready to load up our RESTful CodeIgniter installation, and have a look at the demo supplied with it. Browse the base URL, which by default is:

http://localhost/restserver

Here you will find a few example links to the example_api controller, which can be found at “application/controllers/example_api.php”. Let’s dissect the URL’s of these examples to see what is going on. The first URL is a very simple one.

This URL looks very much like any other CodeIgniter URL with a controller and a method, but you will notice in this diagram that the method is named a “Resource”. REST is all about Resources and they are essentially a noun within your application, which are interacted with (i.e added, deleted, edited, queried) based on HTTP headers and URL query strings or HTTP arguments.

The default format for output is XML which is what we see in this basic example. The other links are slightly larger and demonstrate how to pass parameters and show how the output format can be modified in the URL:

Normally in CodeIgniter, you just pass in parameter values, but a REST controller accepts any number of parameters in any order. For this to work, we need to pass in the name of the parameter followed by the value in pairs.

At the end of the URL is the “format” parameter. This is a reserved parameter that will modify the output format of the requested data like so:

By giving both the API developer and the client application the choice of data formats to use, the API is opened up to a much wider audience and can be used with more programming languages and systems. These three are not the only formats supported, out of the box your REST API can use:

  • xml – almost any programming language can read XML
  • json – useful for JavaScript and increasingly PHP apps.
  • csv – open with spreadsheet programs
  • html – a simple HTML table
  • php – Representation of PHP code that can be eval()’ed
  • serialize – Serialized data that can be unserialized in PHP

While adding the format to the URL is not technically the most RESTful way to change formats, it allows for easy browser testing and lets developers without cURL perform simple GET requests on the API. The more RESTful way is to send a Content-type HTTP header to the REST controller using cURL, but that will be explained later.

Step 3: The Code

Now if you open up application/controllers/example_api.php you will immediatley spot a few differences from normal CodeIgniter controllers.

REST_Controller

In the MVC pattern, a controller is the central point of the logic. It is called when a user makes a request and then based on the logic in the controller it fetches data and outputs views. CodeIgniter contains its own logic for how a Controller should work, but as we are doing something different we need our own REST_Controller library to contain its own REST related logic. So instead of simply using:

<?php
class Example_api extends Controller {

}

…you will need to use:

<?php
require(APPPATH'.libraries/REST_Controller.php');

class Example_api extends REST_Controller {

}

Working with Resources

Now your empty controller is set up, next are the methods or “resources”. This is prossibly the most confusing part of the tutorial if you are used to how CodeIgniter works. Basically, you take the Resource and the HTTP verb and combine them to make a method name. So the two examples we looked at before had a Resource of user and users. Because both of these were loaded in the browser, we know it was using a GET request and so the two methods below are used:

<?php
require(APPPATH'.libraries/REST_Controller.php');

class Example_api extends REST_Controller {

    function user_get()
    {
		// respond with information about a user
    }

    function users_get()
    {
		// respond with information about several users
    }
}

This may seem a little strange, but it gives you the ability to use the same URL and respond to the request depending on the HTTP verb that has been used. If somebody tries to access your API in a way that is not allowed (in this example PUT or DELETE) it will simply respond with a 404. If you aren’t sure about HTTP verbs, let me explain.

GET

Used to fetch information about an existing resource. This is used by browsers when you enter a URL and hit go, or when you click on a link, so it perfect for fetching information on one of your REST resources (like user).

POST

Used to update an existing resource with information. Browsers use this to submit most types of forms on the internet, although some use GET as well by submitting the form action with a query string containing the field data.

PUT

Less commonly used and not supported by most browsers, PUT is used to create a new resource.

DELETE

Also not used by many browsers, this HTTP verb rather obviously is used to delete a resource.

If we put that into code and allow each verb on the resource user it would look like this:

<?php
require(APPPATH'.libraries/REST_Controller.php');

class Example_api extends REST_Controller {

    function user_get()
    {
		// respond with information about a user
    }

    function user_put()
    {
		// create a new user and respond with a status/errors
    }

    function user_post()
    {
		// update an existing user and respond with a status/errors
    }

    function user_delete()
    {
		// delete a user and respond with a status/errors
    }
}

Accessing parameters and returning data

So now the API has been given its structure by setting up the resources and defining a method for each HTTP verb we wish to support; we need parameters so we can use our CodeIgniter models and libraries. This is one of the major benefits of using CodeIgniter for our API, as we can use our existing models and libraries and not have to re-code them.

<?php
require(APPPATH'.libraries/REST_Controller.php');

class Example_api extends REST_Controller {

    function user_get()
    {
		$data = array('returned: '. $this->get('id'));
		$this->response($data);
    }

    function user_post()
    {
		$data = array('returned: '. $this->post('id'));
		$this->response($data);
    }

    function user_put()
    {
		$data = array('returned: '. $this->put('id'));
		$this->response($data;
    }

    function user_delete()
    {
		$data = array('returned: '. $this->delete('id'));
		$this->response($data);
    }
}

This example contains five new pieces of code:

$this->get()

Is used to return GET variables from either a query string like this index.php/example_api/user?id=1 or can be set in the more CodeIgniter’esque way with index.php/example_api/user/id/1.

$this->post()

Is an alias for $this->input->post() which is CodeIgniter’s method to access $_POST variables with XSS protection.

$this->put()

Reads in PUT arguments set in the HTTP headers or via cURL.

$this->delete()

You guessed it, this reads in DELETE arguments, also set in HTTP headers or via cURL.

$this->response()

Sends data to the browser in whichever data format has been requested, or defaults to XML. You can optionally pass a HTTP status code to show it has worked or failed. E.g if the ID provided was not in the database, you could use $this->response(array(‘error’ => ‘User not found.’), 404);

Step 4: Working with your Models

Until now, we have been working with an example API in a clean install. So the next step is to get a REST API running from your existing codebase.

Although the download comes with a full CodeIgniter installation for the demo and to allow API’s to be built from scratch, the only two files of importance are:

  1. application/config/rest.php
  2. application/libraries/REST_Controller.php

Drop those two files into your CodeIgniter application and create a new API controller.

<?php
require(APPPATH.'/libraries/REST_Controller.php');

class Api extends REST_Controller
{
	function user_get()
    {
        if(!$this->get('id'))
        {
        	$this->response(NULL, 400);
        }

        $user = $this->user_model->get( $this->get('id') );

        if($user)
        {
            $this->response($user, 200); // 200 being the HTTP response code
        }

        else
        {
            $this->response(NULL, 404);
        }
    }

    function user_post()
    {
        $result = $this->user_model->update( $this->post('id'), array(
        	'name' => $this->post('name'),
        	'email' => $this->post('email')
        ));

        if($result === FALSE)
        {
        	$this->response(array('status' => 'failed'));
        }

        else
        {
        	$this->response(array('status' => 'success'));
        }

    }

    function users_get()
    {
        $users = $this->user_model->get_all();

        if($users)
        {
            $this->response($users, 200);
        }

        else
        {
            $this->response(NULL, 404);
        }
    }
}
?>

This shows an example API with some generic model names. In the first method, we are picking up a ?id=XX and passing it to the model. If data is found we send it to the $this->response() function with a status 200. If nothing is found, return no body and a 404 to say nothing was found. You can imagine how this could be expanded to run all sorts of API activities for your web application.

Step 5: Securing the API

Now your API is built it needs securing so only users given access can interact with the API. To set the login type, usernames and passwords open up “application/config/rest.php” inside your codebase.

/*
|--------------------------------------------------------------------------
| REST Login
|--------------------------------------------------------------------------
|
| Is login required and if so, which type of login?
|
|	'' = no login required, 'basic' = relatively secure login, 'digest' = secure login
|
*/
$config['rest_auth'] = 'basic';

None

Anyone can interact with any one of of your API controllers.

Basic

A relatively insecure login method which should only be used on internal/secure networks.

Digest

A much more secure login method which encrypts usernames and password. If you wish to have a protected API which anyone could get at, use digest.

/*
|--------------------------------------------------------------------------
| REST Login usernames
|--------------------------------------------------------------------------
|
| Array of usernames and passwords for login
|
|	array('admin' => '1234')
|
*/
$config['rest_valid_logins'] = array('admin' => '1234');

Setting up the users is simple. Each login is an array item, with a key and a value. The key is the username and the value is the password. Add as many as you like to this array and dish them out to anyone who will be using the API.

Part 2 – Interacting with RESTful Services

Whether it is the API you have just built or a public service such as Twitter, you will want to be able to interact with it somehow. Seeing as RESTful services work with basic HTTP requests it is very easy to do this in a number of different ways.

Different Methods to Interact with REST

Each of these different interaction methods will be shown with the code placed directly in the Controller methods. This is purely so the demos are easier to read and would normally would be placed inside a model or a library for correct MVC separation.

file_get_contents()

Using the very simple PHP function file_get_contents(), you can perform a basic GET request. This is the most basic of all the methods but is worth mentioning for those “quick and dirty” moments.

$user = json_decode(
	file_get_contents('http://example.com/index.php/api/user/id/1/format/json')
);

echo $user->name;

It’s worth noting that, while this method will not work using HTTP Digest authentication, if you are using HTTP Basic authentication you can use the following syntax to get data from your password protected RESTful API:

$user = json_decode(
	file_get_contents('http://admin:[email protected]/index.php/api/user/id/1/format/json')
);

echo $user->name;

There are a few problems with using this method: the only way to set extra HTTP headers is to set them manually using the PHP function stream_context_create(), which can be very complicated for developers who are new to the internal workings of HTTP requests. Another disadvantage is that you only receive the body of the HTTP response in its raw format, which means you need to handle conversion from very single request.

cURL

cURL is the most flexible way to interact with a REST API as it was designed for exactly this sort of thing. You can set HTTP headers, HTTP parameters and plenty more. Here is an example of how to update a user with our example_api and cURL to make a POST request:


    function native_curl($new_name, $new_email)
    {
	    $username = 'admin';
		$password = '1234';

		// Alternative JSON version
		// $url = 'http://twitter.com/statuses/update.json';
		// Set up and execute the curl process
		$curl_handle = curl_init();
		curl_setopt($curl_handle, CURLOPT_URL, 'http://localhost/restserver/index.php/example_api/user/id/1/format/json');
		curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl_handle, CURLOPT_POST, 1);
		curl_setopt($curl_handle, CURLOPT_POSTFIELDS, array(
			'name' => $new_name,
			'email' => $new_email
		));

		// Optional, delete this line if your API is open
		curl_setopt($curl_handle, CURLOPT_USERPWD, $username . ':' . $password);

		$buffer = curl_exec($curl_handle);
		curl_close($curl_handle);

		$result = json_decode($buffer);

		if(isset($result->status) && $result->status == 'success')
		{
			echo 'User has been updated.';
		}

		else
		{
			echo 'Something has gone wrong';
		}
    }

Interacting with your API this way works fine, but there are two problems with this method:

  1. It uses an ugly confusing syntax – imagine creating several an application based on that.
  2. cURL is not installed on all servers by default.

To solve this ugly syntax, a cURL library has been developed for CodeIgniter which simplifies things immensely.

The exact same request made with the cURL library would look like this:

    function ci_curl($new_name, $new_email)
    {
	    $username = 'admin';
		$password = '1234';

		$this->load->library('curl');

		$this->curl->create('http://localhost/restserver/index.php/example_api/user/id/1/format/json');

		// Optional, delete this line if your API is open
		$this->curl->http_login($username, $password);

		$this->curl->post(array(
			'name' => $new_name,
			'email' => $new_email
		));

		$result = json_decode($this->curl->execute());

		if(isset($result->status) && $result->status == 'success')
		{
			echo 'User has been updated.';
		}

		else
		{
			echo 'Something has gone wrong';
		}
    }

Much nicer to look at right? Well there is an even easier method to work with REST in your CodeIgniter applications that this.

REST client library

A REST client library has been developed that sits on top of this cURL library which handles format conversion, HTTP logins and several other aspects of your REST API.

    function rest_client_example($id)
    {
		$this->load->library('rest', array(
			'server' => 'http://localhost/restserver/index.php/example_api/',
			'http_user' => 'admin',
			'http_pass' => '1234',
			'http_auth' => 'basic' // or 'digest'
		));

        $user = $this->rest->get('user', array('id' => $id), 'json');

        echo $user->name;
    }

Here you can see we are making a GET request, sending id as a parameter and telling the library we want ‘json’ as the content format. This handles the setting of Content-type for you, and converts the data into a PHP object for you. You can change this value to ‘xml’, ‘json’, ’serialize’, ‘php’, ‘csv’ or any custom MIME-type you like, for example:

	$user = $this->rest->get('user', array('id' => $id), 'application/json');

As you have probably guessed as well as $this->rest->get(), the library also supports $this->rest->post(), $this->rest->put(), $this->rest->delete() to match all of your REST_Controller methods.

You will need to var_dump() results coming from the REST client library to make sure you are getting the right data format back. The conversion will somtimes be array and sometimes be an object, depending on how it is converted by PHP. If the returned MIME-type is not supported then it will simply return the format as plain-text.

Talking to Twitter

Using this REST library you can talk other RESTful services such as Twitter and Facebook. Here is a simple example of how you can get details for a specfic user based on their ID, using Twitter’s default format XML.

        $this->load->library('rest', array('server' => 'http://twitter.com/'));

        $user = $this->rest->get('users/show', array('screen_name' => 'philsturgeon'));
        $this->load->library('rest', array(
        	'server' => 'http://twitter.com/',
			'http_user' => 'username',
			'http_pass' => 'password',
			'http_auth' => 'basic'
        ));

        $user = $this->rest->post('statuses/update.json', array('status' => 'Using the REST client to do stuff'));

Looking at this, you will notice that interacting with the Twitter API is a bit different in a few ways.

  1. They support URL based format switching in the form of .json instead of /format/json. Some require an extension, some do not; so it’s best to always add them.
  2. They mostly only support GET/POST, but are starting to add more DELETE methods
  3. They don’t always have just a resource in their URL, for example: users/search is one REST method, but lists is another.

Keep an eye out for these differences as they can catch you out. If you get stuck, simply echo $this->rest->debug() for a whole range of information on your REST request.

Summary

Combining what you now know about RESTful services, the CodeIgniter REST client library and the Twitter API documentation – or any other RESTful API documentation for that matter – you can create some very powerful applications that integrate with any custom or public web service using REST. You can extend your API by creating more REST_Controller’s and even make a modular API by using Matchbox or Modular Separation to create an api.php controller for each module to help keep your API as neatly organized as your application.

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at [email protected].

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial



Quick Tip: How to Use the New “Post-Thumbnail” Feature in WordPress 2.9

Quick Tip: How to Use the New “Post-Thumbnail” Feature in WordPress 2.9

Up until the release of WordPress 2.9, setting up “post-image” support for your blog was a bit more tedious a task than it really needed to be. Luckily, that’s no longer an issue. I’ll show you how to get setup in this four minute video quick tip.

Step 1. Edit your Functions.php Page

// Enable support for post-thumbnails

add_theme_support('post-thumbnails');

// If we want to ensure that we only call this function if
// the user is working with WP 2.9 or higher,
// let's instead make sure that the function exists first

if ( function_exists('add_theme_support') ) {
	add_theme_support('post-thumbnails');
}

Step 2. Insert the Image Tag into your Loop

Within the “if have_posts()” loop, simply place this piece of code anywhere you like. At that point, WordPress will insert an image tag onto the page accordingly. Please note that you’ll have access to a “wp-post-image” class that you may then work with to format/style the image.

<?php the_post_thumbnail(); ?>




An In-Depth Overview of File Operations in PHP: New Plus Tutorial

An In-Depth Overview of File Operations in PHP: New Plus Tutorial

In this week’s Plus tutorial, we will learn how to work with file operations using PHP. This is one of the most fundamental subjects of server side programming in general. Files are used in web applications of all sizes. So let’s learn how to read, write, create, move, copy, delete files and more. Help give back to Nettuts+, and become a Plus member!

Why You Should Join Plus

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service called “TUTSPLUS”. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Become a Plus member.

  • Subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.



How to Test your JavaScript Code with QUnit

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.

Tutorial Details

  • Language: JavaScript
  • Difficulty: Intermediate
  • Estimated Completion Time: 30 minutes
  • Required File: QUnit JS

What is QUnit

QUnit is a powerful JavaScript unit testing framework that helps you to debug code. It’s written by members of the jQuery team, and is the official test suite for jQuery. But QUnit is general enough to test any regular JavaScript code, and it’s even able to test server-side JavaScript via some JavaScript engine like Rhino or V8.

If you’re unfamiliar with the idea of “unit testing”, don’t worry. It’s not too difficult to understand:

In computer programming, unit testing is a software verification and validation method in which a programmer tests if individual units of source code are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual function or procedure.

This is quoted from Wikipedia. Simply put, you write tests for each functionality of your code, and if all of these tests are passed, you can be sure that the code will be bug-free (mostly, depends on how thorough your tests are).

Why You Should Test Your Code

If you haven’t written any unit tests before, you probably just apply your code to a website directly, click for a while to see if any problem occurs, and try to fix it as you spot one. There are many problems with this method.

First, it’s very tedious. Clicking actually is not an easy job, because you have to make sure everything is clicked and it’s very likely you’ll miss one thing or two. Second, everything you did for testing is not reusable, which means it’s not easy to find regressions. What is a regression? Imagine that you wrote some code and tested it, fixed all the bugs you found, and published it. Then, a user sends some feedback about new bugs, and requests some new features. You go back to the code, fix these new bugs and add these new features. What might happen next is that some of the old bugs come up again, which are called “regressions.” See, now you have to do the clicking again, and chances are you won’t find these old bugs again; even if you do, it’ll take a while before you figure out that the problem is caused by regressions. With unit testing, you write tests to find bugs, and once the code is modified, you filter it through the tests again. If a regression appears, some tests will definitely be failed, and you can easily spot them, knowing which part of the code contains the bug. Since you know what you have just modified, it can easily be fixed.

Another advantage of unit testing is especially for web development: it eases the testing of cross-browser compatibility. Just run your tests on different browsers, and if a problem occurs on one browser, you fix it and run these tests again, making sure it doesn’t introduce regression on other browsers. You can be sure that all of the target browsers are supported, once they all pass the tests.

I’d like to mention one of John Resig’s projects: TestSwarm. It takes JavaScript unit testing to a new level, by making it distributed. It’s a website that contains many tests, anyone can go there, run some of the tests, then return the result back to server. In this way, code can be tested on different browsers and even different platforms really quickly.

How to Write Unit Tests with QUnit

So how do you write unit tests with QUnit exactly? First, you need to set up a testing environment:

<!DOCTYPE html>
<html>
<head>
	<title>QUnit Test Suite</title>
	<link rel="stylesheet" href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css" type="text/css" media="screen">
	<script type="text/javascript" src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"></script>
	<!-- Your project file goes here -->
	<script type="text/javascript" src="myProject.js"></script>
	<!-- Your tests file goes here -->
	<script type="text/javascript" src="myTests.js"></script>
</head>
<body>
	<h1 id="qunit-header">QUnit Test Suite</h1>
	<h2 id="qunit-banner"></h2>
	<div id="qunit-testrunner-toolbar"></div>
	<h2 id="qunit-userAgent"></h2>
	<ol id="qunit-tests"></ol>
</body>
</html>

As you can see, a hosted version of QUnit framework is used here.

The code that is going to be tested should be put into myProject.js, and your tests should be inserted into myTests.js. To run these tests, simply open this HTML file in a browser. Now it’s time to write some tests.

The building blocks of unit tests are assertions.

An assertion is a statement that predicts the returning result of your code. If the prediction is false, the assertion has failed, and you know that something has gone wrong.

To run assertions, you should put them into a test case:

// Let's test this function
function isEven(val) {
	return val % 2 === 0;
}

test('isEven()', function() {
	ok(isEven(0), 'Zero is an even number');
	ok(isEven(2), 'So is two');
	ok(isEven(-4), 'So is negative four');
	ok(!isEven(1), 'One is not an even number');
	ok(!isEven(-7), 'Neither is negative seven');
})

Here we defined a function, isEven, which detects whether a number is even, and we want to test this function to make sure it doesn’t return wrong answers.

We first call test(), which constructs a test case; the first parameter is a string that will be displayed in the result, and the second parameter is a callback function that contains our assertions. This callback function will get called once QUnit is run.

We wrote five assertions, all of which are boolean. A boolean assertion expects its first parameter to be true. The second parameter is also a message that will be displayed in the result.

Here is what you get, once you run the test:

a test for isEven()

Since all these assertions have successfully passed, we can be pretty sure that isEven() will work as expected.

Let’s see what happens if an assertion has failed.

// Let's test this function
function isEven(val) {
	return val % 2 === 0;
}

test('isEven()', function() {
	ok(isEven(0), 'Zero is an even number');
	ok(isEven(2), 'So is two');
	ok(isEven(-4), 'So is negative four');
	ok(!isEven(1), 'One is not an even number');
	ok(!isEven(-7), 'Neither does negative seven');

	// Fails
	ok(isEven(3), 'Three is an even number');
})

Here is the result:

a test contains failed assertion for isEven()

The assertion has failed because we deliberately wrote it wrong, but in your own project, if the test doesn’t pass, and all assertion are correct, you know a bug has been found.

More Assertions

ok() is not the only assertion that QUnit provides. There are other kinds of assertions that are useful when testing your project:

Comparison Assertion

The comparison assertion, equals(), expects its first parameter (which is the actual value) is equal to its second parameter (which is the expected value). It’s similar to ok(), but outputs both actual and expected values, making debugging much easier. Like ok(), it takes an optional third parameter as a message to be displayed.

So instead of:

test('assertions', function() {
	ok( 1 == 1, 'one equals one');
})
a boolean assertion

You should write:

test('assertions', function() {
	equals( 1, 1, 'one equals one');
})
a comparison assertion

Notice the last “1″, which is the comparing value.

And if the values are not equal:

test('assertions', function() {
	equals( 2, 1, 'one equals one');
})
a failed comparison assertion

It gives a lot more information, making life a lot easier.

The comparison assertion uses “==” to compare its parameters, so it doesn’t handle array or object comparison:

test('test', function() {
	equals( {}, {}, 'fails, these are different objects');
	equals( {a: 1}, {a: 1} , 'fails');
	equals( [], [], 'fails, there are different arrays');
	equals( [1], [1], 'fails');
})

In order to test this kind of equality, QUnit provides another kind assertion: identical assertion.

Identical Assertion

Identical assertion, same(), expects the same parameters as equals(), but it’s a deep recursive comparison assertion that works not only on primitive types, but also arrays and objects. Assertions, in the previous example, will all pass if you change them to identical assertions:

test('test', function() {
	same( {}, {}, 'passes, objects have the same content');
	same( {a: 1}, {a: 1} , 'passes');
	same( [], [], 'passes, arrays have the same content');
	same( [1], [1], 'passes');
})

Notice that same() uses ‘===’ to do comparison when possible, so it’ll come in handy when comparing special values:

test('test', function() {
	equals( 0, false, 'true');
	same( 0, false, 'false');
	equals( null, undefined, 'true');
	same( null, undefined, 'false');
})

Structure Your Assertions

Putting all assertions in a single test case is a really bad idea, because it’s very hard to maintain, and doesn’t return a clean result. What you should do is to structure them, put them into different test cases, each aiming for a single functionality.

You can even organize test cases into different modules by calling the module function:

module('Module A');
test('a test', function() {});
test('an another test', function() {});

module('Module B');
test('a test', function() {});
test('an another test', function() {});
structure assertions

Asynchronous Test

In previous examples, all assertions are called synchronously, which means they run one after another. In the real world, there are also many asynchronous functions, such as ajax calls or functions called by setTimeout() and setInterval(). How can we test these kinds of functions? QUnit provides a special kind of test case called “asynchronous test,” which is dedicated to asynchronous testing:

Let’s first try to write it in a regular way:

test('asynchronous test', function() {
	setTimeout(function() {
		ok(true);
	}, 100)
})
an incorrent example of asychronous test

See? It’s as if we didn’t write any assertion. This is because the assertion ran asynchronously, by the time it got called, the test case had already finished.

Here is the correct version:

test('asynchronous test', function() {
	// Pause the test first
	stop();

	setTimeout(function() {
		ok(true);

		// After the assertion has been called,
		// continue the test
		start();
	}, 100)
})
a correct example of asychronous test

Here, we use stop() to pause the test case, and after the assertion has been called, we use start() to continue.

Calling stop() immediately after calling test() is quite common; so QUnit provides a shortcut: asyncTest(). You can rewrite the previous example like this:

asyncTest('asynchronous test', function() {
	// The test is automatically paused

	setTimeout(function() {
		ok(true);

		// After the assertion has been called,
		// continue the test
		start();
	}, 100)
})

There is one thing to watch out for: setTimeout() will always call its callback function, but what if it’s a custom function (e.g, an ajax call). How can you be sure the callback function will be called? And if the callback is not called, start() won’t be called, and the whole unit testing will hang:

unit testing hangs

So here is what you do:

// A custom function
function ajax(successCallback) {
	$.ajax({
		url: 'server.php',
		success: successCallback
	});
}

test('asynchronous test', function() {
	// Pause the test, and fail it if start() isn't called after one second
	stop(1000);

	ajax(function() {
		// ...asynchronous assertions

		start();
	})
})

You pass a timeout to stop(), which tells QUnit, “if start() isn’t called after that timeout, you should fail this test.” You can be sure that the whole testing won’t hang and you’ll be notified if something goes wrong.

How about multiple asynchronous functions? Where do you put the start()? You put it in setTimeout():

// A custom function
function ajax(successCallback) {
	$.ajax({
		url: 'server.php',
		success: successCallback
	});
}

test('asynchronous test', function() {
	// Pause the test
	stop();

	ajax(function() {
		// ...asynchronous assertions
	})

	ajax(function() {
		// ...asynchronous assertions
	})

	setTimeout(function() {
		start();
	}, 2000);
})

The timeout should be reasonably long enough to allow both callbacks to be called before the test continues. But what if one of the callback isn’t called? How can you know that? This is where expect() comes in:

// A custom function
function ajax(successCallback) {
	$.ajax({
		url: 'server.php',
		success: successCallback
	});
}

test('asynchronous test', function() {
	// Pause the test
	stop();

	// Tell QUnit that you expect three assertions to run
	expect(3);

	ajax(function() {
		ok(true);
	})

	ajax(function() {
		ok(true);
		ok(true);
	})

	setTimeout(function() {
		start();
	}, 2000);
})

You pass in a number to expect() to tell QUnit that you expect X many assertions to run, if one of the assertion isn’t called, the number won’t match, and you’ll be notified that something went wrong.

There is also a shortcut for expect(): you just pass the number as the second parameter to test() or asyncTest():

// A custom function
function ajax(successCallback) {
	$.ajax({
		url: 'server.php',
		success: successCallback
	});
}

// Tell QUnit that you expect three assertion to run
test('asynchronous test', 3, function() {
	// Pause the test
	stop();

	ajax(function() {
		ok(true);
	})

	ajax(function() {
		ok(true);
		ok(true);
	})

	setTimeout(function() {
		start();
	}, 2000);
})

Conclusion

That’s all you need to know to get started witih QUnit. Unit testing is a great method to test your code before publishing it. If you haven’t written any unit tests before, it’s time to get started! Thanks for reading!



Highly Recommended Services and Apps: CodeCanyon Sponsors

Highly Recommended Services and Apps: CodeCanyon Sponsors

As most of you know by now, we’re hosting an enormous competition to celebrate the recent launch of CodeCanyon. The $6200 worth of prizes simply wouldn’t have been possible without the generosity of our sponsors. Luckily, I can also say that I 100% recommend each and every one of the services/products listed below.

Media Temple

“Media Temple hosts websites. Big and Small. For years we’ve taken complex technology and simplified it for the everyday website owner. Our products are designed to be powerful, affordable and relevant. Please take a look around; perhaps (mt) is a good choice for your next project.”

They’re who I personally use for all my hosting needs.

TechSmith

“We create screen capture and recording software to help you communicate clearly and effectively, deliver engaging presentations, analyze usability and conduct market research.

For over 20 years, we’ve helped people communicate visually and look great doing it.”

I use Camtasia Mac for every weekly screencast on this site!

Wufoo

“Wufoo strives to be the easiest way to collect information over the Internet.

Our HTML form builder helps you create contact forms, online surveys, and invitations so you can collect the data, registrations and online payments you need without writing a single line of code.”

Envato uses Wufoo for its invoicing system.

FormSpring

“FormSpring’s easy form builder gives businesses and organizations an easy way to build any type of online form, integrate it with their website and begin collecting data. Once you have started collecting that data you can use the information you gathered in our online database or export it. With FormSpring anyone can build all types of web forms, collect data online and do it simply and efficiently.”

We use FormSpring for our tutorial submission forms. Visit Web.Appstorm for a full review.

Surreal CMS

“With Surreal CMS, there’s absolutely nothing to install. Just enter your website’s FTP info and you’re connected! Within minutes, you can enable webpages, add content regions, assign editors, and begin updating your website — and you don’t even need an FTP client to get started!”

TypeKit

“This will change the way you design websites.

Add a line of code to your pages and choose from hundreds of fonts. Simple, bulletproof, standards compliant, accessible, and totally legal.”

Watch a screencast on Nettuts+ demonstrating just how easy it is to work with.

Myows

“It’s an easy-to-use app dedicated to providing a full suite of copyright solutions, from registration to management.

Myows has been created for designers, photographers, bloggers, writers, musicians and anyone who creates copyrightable work.”

We recommend that authors on ThemeForest use this service!

Snippet

“Easily create (code) Snippets from selected text anywhere.”

Read a full review from Mac.Appstorm.

Threadsy

“Threadsy is a new kind of messaging experience created for anyone to use. it combines all of your existing accounts in one place and enhances them with relevant information from your social networks and the public web. the effect is a brand new flavor of communication harmony.”

I’ve been using Threadsy Beta for over a week now, and have high hopes for the official release! Visit Web.AppStorm for a full review.

Rockable Press

“At Rockable Press, we produce simple, straight forward how-to guides and resources for web and creative professionals. We are a small web publishing outfit operated by Envato with authors based around the world.”