jQuery.Deferred to Tell When Certain iframes Are Loaded

Since jQuery 1.5 came out I’ve been intrigued about the new jQuery.Deferred feature, but hadn’t used it until now. You might think that Deferreds are isolated to only jQuery.ajax requests, but they are much more flexible than that. jQuery.ajax utilize defferds, but you can also use them to define your own set of promises.
<blockquote>Eric Hynds wrote an awesome blog post entitled Using Deferreds in jQuery 1.5 describing the inns and outs of jQuery Deferreds in much more detail, but I thought I’d share a use case that I found helpful in a recent project.</blockquote>I’m working on a project where there are multiple hidden iframes loaded on the page (don’t ask why LOL) and I needed a way to tell if they were all loaded. Almost immediately I thought about using the new Deferred feature!

<pre>(function($) {

function iFrameLoaded( id, src ) {
var deferred = $.Deferred(),
iframe = $( “” ).attr({
“id”: id,
“src”: src

iframe.load( deferred.resolve );
iframe.appendTo( “body” );

deferred.done(function() {
console.log( “iframe loaded: “ + id );

return deferred.promise();

iFrameLoaded(“jQuery”, “http://jquery.com”),
iFrameLoaded(“appendTo”, “http://appendto.com”))
.then( function() {
console.log( “Both iframes loaded” );

The above code creates a new jQuery.Deferred object (line 4) and iframe element. Once the iframe is loaded, we tell the deferred object to resolve itself (line 10). At that point we define our own event handler to respond to when the deferred is done (line 13). In this case we just print to the console that “iframe loaded”. Then we return the deferred promise (line 17) so that we can use it in the new jQuery.when method.

Next we call the jQuery.when method (line 20) and pass all the promises we want fulfilled before we proceed. Once all the iframes are loaded, then the then method will execute (line 23) printing out “Both iframes loaded” to the console.

View Demo Edit Demo

<blockquote>Note: This same concept can also be applied to a set of images loading and many other applications.</blockquote>

Read More »

ASPInsiders Twitter List

The ASPInsiders is a select group of international professionals in ASP.NET technologies (Web Forms, MVC, Web Pages, etc…)

Jason Gaylord has assembled a list of ASPInsiders into a new ASPInsiders Twitter List that you can follow to keep track of the latest in ASP.NET technologies.

<blockquote>“The ASPInsiders team spends countless hours answering questions and giving guidance to other ASP.NET developers, as well as providing feedback and diretion on new features for future ASP.NET releases. Their work and contributions are invaluable.” </blockquote><blockquote><div>Scott Guthrie </div><div>Product Unit Manger, Web Platforms, Microsoft Corporation</div></blockquote>

ASPInsiders Twitter List

<blockquote>Note: The ASPInsiders group is different from the Microsoft MVP award. Many of the ASPInsiders either are or have been a Microsoft MVP as well, but there are also many that have not. There is not a 1:1 correlations between the two groups.  </blockquote>

Read More »

Free Julian on JavaScript Series

If you are new to JavaScript or just don’t know it as well as you should, then I encourage you to watch the Julian on JavaScript Series on DevExpress.

Julian M Bucknall wrote an awesome series a while back called JavaScript for C# Developers that I remember going through that helped me become a better JavaScript developer.

Julian has planned out 4 sessions thus far, and has completed one of them already. If you can’t make the live webinar, then the sessions will be available to view online afterwards.

Julian on JavaScript I (07-Feb-2011)

Writing JavaScript when you already know C# can seem like a piece of cake: after all it’s a C-like language, so what can go wrong? Julian starts off a series of webinars to teach you the basics of writing JavaScript. No experience is necessary apart from an understanding of C#. This webinar will concentrate on types.

Watch Online

Julian on JavaScript II (28-Feb-2011)

Writing JavaScript when you already know C# can seem like a piece of cake: after all it’s a C-like language, so what can go wrong? Julian continues a series of webinars that teach you the basics of writing JavaScript. This webinar will concentrate on objects and assumes you’ve watched part I.

Register Online

Julian on JavaScript III (07-Mar-2011)

Writing JavaScript when you already know C# can seem like a piece of cake: after all it’s a C-like language, so what can go wrong? Julian continues a series of webinars that teach you the basics of writing JavaScript. This webinar will concentrate on functions and assumes you’ve watched parts I and II.

Register Online

Julian on JavaScript IV (28-Mar-2011)

Writing JavaScript when you already know C# can seem like a piece of cake: after all it’s a C-like language, so what can go wrong? Julian continues a series of webinars that teach you the basics of writing JavaScript. This webinar will dive deep into writing good JavaScript and assumes you’ve watched the previous three parts.

Register Online

Read More »

Mocking jQuery Ajax Calls with Random Templated Data

In a recent blog post, Mocking the jQuery Ajax Call in ASP.NET MVC 3 Music Store , I showed you how you could use the $.mockjax library, written by Jonathan Sharp, to intercept AJAX requests and return a mocked response. This tool can be especially useful when trying to code your front-end, while the back-end piece is either isn’t available or accessible.

Another useful library that you may consider when building quick prototypes is $.mockJSON, written by Menno van Slooten. This library has some of the same features as $.mockjax, but the piece I’d like to focus on is the random data tempting feature. This can be very handy when you want to mock a JSON response from a AJAX call, but instead of manually building the response you can build a template to do it for you.

To demonstrate using this random data technique, I decided to use the SlickGrid jQuery Plugin and populate it with the JSON response from an AJAX call. Since the AJAX call doesn’t exist, I am going to use $.mockjax to return the response using random data generated from $.mockJSON.

The following code is what is necessary to populate the SlickGrid with data from an AJAX call.

<pre>(function($) {

var grid,
columns = [
{id:”firstName”, name:”First Name”, field:”firstName”, width:70},
{id:”lastName”, name:”Last Name”, field:”lastName”, width:70},
{id:”email”, name:”Email”, field:”email”, width:170},
{id:”percentHealth”, name:”% Health”, field:”percentHealth”, width:90, formatter:GraphicalPercentCompleteCellFormatter},
{id:”birthday”, name:”Birthday”, field:”birthday”, width:70},
{id:”married”, name:”Married”, field:”married”, width:50, formatter:BoolCellFormatter}
options = {
editable: false,
enableAddRow: false,
enableCellNavigation: true,
rowCssClasses: function(item) {
return (item.percentHealth >= 80) ?
“healthy” : “”;

url: “/Contact/List”,
type: “GET”,
dataType: “json”,
success: function(data, textStatus, xhr) {
grid = new Slick.Grid(“#myGrid”,
data.contacts, columns, options);
error: function(xhr, textStatus, errorThrown) {
console.log(“Error: “ + textStatus);

function BoolCellFormatter(row, cell, value,
columnDef, dataContext) {
return value ? “✔” : “”;

</pre>At this point, I don’t have the '/Contact/List' endpoint defined so if I executed the above code I would get a GET http://fiddle.jshell.net/Contact/List 404 (NOT FOUND) error in my console. If I did want to test the behavior of my front-end without depending on a back-end existing, then I can add an additional $.mockjax statement to intercept the call and respond with some random data provided by $.mockjson.

url: ‘/Contact/List’,
responseTime: 750,
responseText: $.mockJSON.generateFromTemplate({
50-500”: [{
0-1”: true,
“email” : “@EMAIL”,
“firstName”: “@MALE_FIRST_NAME”,
“lastName”: “@LAST_NAME”,
“birthday”: “@DATE_MM/@DATE_DD/@DATE_YYYY”,
0-100”: 0
</pre>The above code will intercept any AJAX requests with the '/Contact/List' endpoint and will use the template passed to $.mockJSON as the response. The template will generate between 50 and 500 contacts each having male first names and having a health ranging from 0 to 100. Each contact will have a random email, birthday, and married boolean field. You can find out more information as to what $.mockJSON supports and how you can extend it from their website.

The following JSON snippet is an example of what the above $.mockJSON template will generate. The above template would generate between 50 to 500 contacts, but for brevity I just included 4.

“contacts”: [{
“married”: false,
“email”: “u.lewis@gonzalez.com”,
“firstName”: “Paul”,
“lastName”: “Martinez”,
“birthday”: “12/16/2005”,
“percentHealth”: 37},
“married”: false,
“email”: “k.hernandez@smith.com”,
“firstName”: “Daniel”,
“lastName”: “Gonzalez”,
“birthday”: “07/11/1997”,
“percentHealth”: 1},
“married”: true,
“email”: “c.thomas@taylor.com”,
“firstName”: “David”,
“lastName”: “Lewis”,
“birthday”: “04/13/2007”,
“percentHealth”: 62},
“married”: true,
“email”: “v.davis@lee.com”,
“firstName”: “Richard”,
“lastName”: “Rodriguez”,
“birthday”: “05/10/2007”,
“percentHealth”: 6}]

//A bunch more…

</pre>Now, since we have some data coming back from our AJAX request, we can run our code again and proceed to get our front-end working as intended.

View Demo Edit Demo

Read More »

Mocking the jQuery Ajax Call in ASP.NET MVC 3 Music Store

Sometimes the front-end and back-end of your application progress at different speeds. In order for each layer to progress independently it is optimal if the front-end piece can mock the results of the back-end.

I have grabbed the AJAX section from the recently updated ASP.NET MVC 3 Music Store and I slightly tweaked it below.

<pre>$(“.RemoveLink”).click(function() {
var recordToDelete = $(this).attr(“data-id”);

if (recordToDelete) {
$.post(“/ShoppingCart/RemoveFromCart”, {
“id”: recordToDelete
}, function(data) {
if (data.ItemCount === 0) {
$(‘#row-‘ + data.DeleteId).fadeOut(‘slow’);
} else {
$(‘#item-count-‘ + data.DeleteId)

.text(‘Cart (‘ + data.CartCount + ‘)’);
Let’s say for example, that the controller action wasn’t yet implemented, but the front-end developer still wanted to progress in their code. To do this we are going to introduce a new tool called Mockjax to simulate a response from a jQuery ajax call.

The following code mocks any call to the /ShoopingCart/RemoveFromCart URL and will respond with the following object literal.

url: “/ShoppingCart/RemoveFromCart”,
responseTime: 750,
responseText: {
ItemCount: 5,
DeleteId: 1,
CartTotal: 112.45,
Message: “Your cart has been updated!”,
CartCount: 16
The great thing about the above technique is that you are guaranteed the same response will be returned no matter what request you made to the ajax call. For example, this approach can be very good for Unit Testing. However, if you are trying to demonstrate the code to a client or just want to play around with the behavior then you might want something a little more flexible and dynamic.

Fortunately, Mockjax not only allows you to return a static set of responseText or repsonseXML, but it also lets you dynamically decide what content you want returned, which is what we are going to demonstrate below.
<blockquote>Note: Mockjax offers much more control than what I am showing in this example. I encourage you to check out all of it’s features.</blockquote><pre>$.mockjax({
url: “/ShoppingCart/RemoveFromCart”,
responseTime: 750,
response: function(settings) {
var row = $(“#row-“ + settings.data.id),
itemCount = +row.find(“td”).eq(2)
.text(function(index, text) {
return +$.trim(text) - 1;
cartTotal = 0, cartCount = 0;

$(“table tr”).each(function(index, element) {
var row = $(element),
price = +row.find(“td”).eq(1).text(),
quantity = +row.find(“td”).eq(2).text();

if (price && quantity) {
cartCount += quantity;
cartTotal += price * quantity;

this.responseText = {
ItemCount: itemCount,
DeleteId: settings.data.id,
CartTotal: cartTotal.toFixed(2),
Message: “Your cart has been updated!”,
CartCount: cartCount
This might seem like excessive front-end code, but the intent is to simulate what the back-end might return in order for the front-end to respond in an appropriate manner. The code is doing some basic calculations to determine what the Shopping Cart quantity and values might be after deleting an item.
<blockquote>Note: The mockjax response code above could have been simplified somewhat if I had modified the MVC 3 View rendering the HTML, but as in many projects you don’t always have access to change the existing output. I decided to go with that approach instead of changing the MVC 3 View code in this blog post. </blockquote>
Once the back-end code is complete, then you can remove the $.mockjax call from your code-base and it will be hitting your back-end resource instead of the mocked response.

I captured the HTML, CSS, and JavaScript from the MVC 3 Music Store and put it in the following jsFiddle for you to execute and play around with. The main piece that I added was the mockjax code to simulate the AJAX request and response from the server.

<blockquote>Note: You might also consider mockjax to be a great Unit Testing tool as you are developing your front-end code and the back-end isn’t yet implemented.</blockquote>

Read More »