Blog Archives

$(document).ready() and pageLoad() are not the same!

Recently, I’ve attended several presentations in which ASP.NET AJAX’s pageLoad() shortcut is demonstrated as interchangeable with jQuery’s $(document).ready() event. The suggestion that both methods are equivalent actually appears to be true in simple demos, but is not the case and is certain to lead to later confusion.

While they seem similar on the surface, $(document).ready() and pageLoad() are very different behind the scenes. Determining the earliest point that it’s safe to modify the DOM requires a bit of black magic, and the two libraries approach that in their own unique ways. Additionally, pageLoad() is overloaded with some extra functionality which may surprise you.

In this post, I’ll clarify the major differences between jQuery and ASP.NET AJAX’s initialization functions, what implications those difference have in practice, and show you a third alternative when working with ASP.NET AJAX.

Under the hood: $(document).ready()

As you would expect from John Resig, jQuery’s method for determining when the DOM is ready uses an assortment of optimizations.

For example, if a browser supports the DOMContentLoaded event (as many non-IE browsers do), then it will fire on that event. However, IE can’t safely fire until the document’s readyState reaches “complete”, which is typically later.

If none of those optimizations are available, window.onload will trigger the event.

Under the hood: pageLoad()

Instead of targeting browser-specific optimizations, the ASP.NET AJAX pageLoad() shortcut function is called as a result of a more uniform process.

That process is queued up the same way on all browsers, via a call to setTimeout with a timeout of 0 milliseconds. This trick leverages JavaScript’s single-threaded execution model to (theoretically) push the init event back until just after the DOM has finished loading.

Counter-intuitively, this isn’t the only point at which pageLoad() is called. It is also called after every partial postback. It basically functions as a combination of Application.Init and PageRequestManager.EndRequest.

Danger: UpdatePanels ahead

Since pageLoad() is called after every UpdatePanel refresh, the complications that arise can be initially difficult to grasp. For example, you’ll often see code like this:

<script type="text/javascript">
  function pageLoad() {
    // Initialization code here, meant to run once. 
  }
</script>
 
<asp:ScriptManager runat="server" />
 
<asp:UpdatePanel runat="server">
  <ContentTemplate>
    <asp:Button runat="server" ID="Button1" />
    <asp:Literal runat="server" ID="TextBox1" />
  </ContentTemplate>
</asp:UpdatePanel>

That initialization code will execute on the initial load, and things will seem okay at first. However, pageLoad() will then continue to be called each time Button1 is triggered, resulting in the initialization code running more often than intended.

This problem is similar to the classic ASP.NET mistake of forgetting to test for IsPostBack during the server-side Page_Load event. Depending on the nature of your initialization code, you may not even notice that there’s a problem, but it’s bound to catch up with you eventually.

In the case of initialization code that should run once, $(document).ready() is the ideal solution. It will do exactly what you need and nothing more.

Sometimes, pageLoad() is exactly what you want

While $(document).ready() is ideal for one-time initialization routines, it leaves you hanging if you have code that needs to be re-run after every partial postback. The LiveQuery functionality added in jQuery v1.3+ helps with this, but only works for a limited set of functionality.

For example, what if we wanted to add a jQueryUI datepicker to the TextBox in the previous example? Adding it in $(document).ready() would work great, until a partial postback occurred. Then, the UpdatePanel’s new TextBox element would no longer have the datepicker wired up to it. This is exactly where pageLoad() shines:

<script type="text/javascript">
  function pageLoad() {
    $('#TextBox1').unbind();
    $('#TextBox1').datepicker();
  }
</script>
 
<asp:ScriptManager runat="server" />
 
<asp:UpdatePanel runat="server">
  <ContentTemplate>
    <asp:Button runat="server" ID="Button1" />
    <asp:TextBox runat="server" ID="TextBox1" />
  </ContentTemplate>
</asp:UpdatePanel>

By attaching in pageLoad(), our TextBox will now have the datepicker attached to it on initial page load, and have it re-attached after every partial postback.

The call to unbind() is optional in this case, but a good precaution on more complex pages. Else, you run the risk of stacking multiple events on elements that were not refreshed as part of the partial postback.

An ASP.NET AJAX alternative to $(document).ready()

The previous sections should make it easier to decide between jQuery and ASP.NET AJAX’s events, but they assume you’re using both frameworks. What if you’re only using ASP.NET AJAX and want functionality similar to $(document).ready()?

Luckily, ASP.NET AJAX does provide a corresponding event. The Application.Init event fires only one time per page load, and is perfect for onetime initialization tasks. It’s not available through a shortcut function and requires slightly more caution, but serves its purpose:

<asp:ScriptManager runat="server" />
 
<script type="text/javascript">
  Sys.Application.add_init(function() {
    // Initialization code here, meant to run once.
  });
</script>

Note that the call to Application.add_init is placed after the ScriptManager. This is necessary because the ScriptManager injects its reference to MicrosoftAjax.js in that location. Attempting to reference the Sys object before that point will result in a “sys is undefined” JavaScript error.

If you think that limitation is a bit messy, you are not alone. I’m not a big fan of littering my presentation code with any more inline JavaScript than is necessary. To avoid this clutter, you may alternatively include your Application.Init code in an external file, included via a ScriptReference (see the previous link for an example).

Summary (tl;dr)

$(document).ready()

  • Ideal for onetime initialization.
  • Optimization black magic; may run slightly earlier than pageLoad().
  • Does not re-attach functionality to elements affected by partial postbacks.

pageLoad()

  • Unsuitable for onetime initialization if used with UpdatePanels.
  • Slightly less optimized in some browsers, but consistent.
  • Perfect for re-attaching functionality to elements within UpdatePanels.

Application.Init

  • Useful for onetime initialization if only ASP.NET AJAX is available.
  • More work required to wire the event up.
  • Exposes you to the “sys is undefined” error if you aren’t careful.

###

Originally posted at Encosia. If you’re reading this elsewhere, come on over and see the original.

$(document).ready() and pageLoad() are not the same!

Use jQuery to catch and display ASP.NET AJAX service errors

Another user fed up with your lack of error handling!

If you don’t properly handle the inevitable errors in your web applications, you can expect your users to eventually react about like this guy. Since they typically squelch any server-side errors, AJAX service calls are especially problematic. In fact, they rarely even throw a client-side error when they fail.

Even when a client-side error is thrown, most users won’t notice it and the ones who do notice won’t know what the error means or what to do next. In fact, I’ve found that even many developers don’t notice client-side scripting errors that occur while they’re debugging their own applications!

To help you remedy this problem in your own applications, I want to show you one way that I handle AJAX service call errors with jQuery. To do this, we will build an error-prone web service, make an AJAX request to it via jQuery, handle the resulting server-side errors gracefully, and use a jQuery plugin to attractively present those errors.

Building an erroneous method

To experiment with error handling, the first thing we’ll need is an error. We could use throw() to raise a synthetic error, but let’s build a page method that’s apt to throw a couple of real errors:

[WebMethod]
public static int DivideByZero(int Dividend)
{
  // To fool the compiler into not saving us from ourselves.
  int zero = 0;
 
  return (Dividend / zero);
}

If this method is called with a parameter that cannot be parsed as an integer, it will throw a type conversion error. If we do correctly call it with a string that can be converted to an integer, we’ll get a division by zero exception.

Using jQuery to call the page method

To interface with the page method, we’ll need an input field to supply the dividend and a button to trigger a call to the page method. Something like this:

<html>
<head>
  <title>Division by Zero Utility v1.0</title>
  <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
  <script type="text/javascript" src="default.js"></script>
</head>
<body>
  <input type="text" id="Dividend" />
  <input type="button" id="Divide" value="Divide by 0" />
</body>
</html>

Using jQuery to call an ASP.NET AJAX page method is easy once you understand the required syntax and a few quirks. In default.js, we can use jQuery’s click() to wire our DivideByZero method up to the input button’s click event:

/// <reference path="~/jquery-1.3.2-vsdoc.js />
// When the page loads...
$(document).ready(function() {
  // ...attach an onclick handler to the Divide button.
  $("#Divide").click(function() {
    // Trigger a request to the page method.
    $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      url: "Default.aspx/DivideByZero",
      // Supply the Dividend value from our input field.
      data: "{ 'Dividend': '" + $("#Dividend").val() + "' }",
      // Error!
      error: function(xhr, status, error) {
        // Display a generic error for now.
        alert("AJAX Error!");
      }
    });
  });
});

Notice the error callback function. This function will be raised in the event of any error or timeout when calling the service. For now, we’ll just display an alert() with a static error message.

If you were to run this example now, typing anything in the input field and hitting the “Divide by 0” button will result in the error handler being called. That’s better than nothing, but wouldn’t it be more useful to display specific information about the exception that occurred?

Inspecting the server’s response in Firebug

To improve the detail of our message, we need to dissect the error returned by the server and find where the specific detail lies. To accomplish this most effectively, I recommend using the Firebug addon to Firefox.

Using Firebug to set a breakpoint on the error handler, we’re able to inspect the request’s state at that point and quickly drill down to the information we’re after:

Inspecting the error's state, using a breakpoint in Firebug

While the status of “error” may seem unhelpful, it is a useful bit of information in some cases. In a more sophisticated error handling scenario, it would allow us to distinguish between a server-side error and a timeout.

However, the undefined error parameter certainly is not helpful.

To find the detail that we need, we’ll have to explore a bit further. Our request’s XMLHttpRequest instance should contain what we’re looking for. Clicking on the green XMLHttpRequest text will shift the Firebug window to inspect that specific object in detail:

Inspecting the XMLHttpRequest object in Firebug

Now we’re getting there: The XMLHttpRequest’s responseText property contains a JSON object with all the detail that the server returned.

As you can see in the Firebug screenshot, the Message variable contains a more familiar .NET error. In this case, indicating that the empty string I submitted was unsuitable for conversion to the Int32 parameter that DivideByZero expects.

Making effective use of the error data

As a string, this JSON object isn’t quite what we need. The last thing we should do is try to parse the error message ourselves. While technically possible, it would be messy and prone to breakage, or require using an extra library such as json2.js.

One of the nice things about JSON is that it is a native JavaScript construct. Thus, JavaScript’s eval() will evaluate a JSON string and return an actual JSON object.

To take advantage of that, we can modify the error handler like this:

error: function(xhr, status, error) {
  // Boil the ASP.NET AJAX error down to JSON.
  var err = eval("(" + xhr.responseText + ")");
 
  // Display the specific error raised by the server (e.g. not a
  //   valid value for Int32, or attempted to divide by zero).
  alert(err.Message);
}

Now, the properties of the error that we got a glimpse of in Firebug are available via the same dot-notation that you’d expect from any object. In particular, the errors returned by ASP.NET AJAX provide three variables in their JSON response: ExceptionType, Message, and StackTrace.

Note: I would normally recommend against using eval() to evaluate a JSON string. However, it is relatively safe in this case since these messages come directly from the .NET framework and do not contain any user-injected content.

Presenting the error message with jQuery

I’ve written about Mike Alsup’s BlockUI plugin before, showing you how to use it to display modal progress indication and confirmation windows. An often overlooked feature of the plugin is the ability to display basic “growl” style notifications.

See the demo at the bottom of this page for an example of that.

After adding a script reference to blockUI.js, displaying the error “growl” couldn’t be easier:

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
 
  // Display the error "growl", with a title of "Error",
  //  the error message as content, and a 20s display time.
  $.growlUI('Error', err.Message, 20000);
},
success: function() {
  // On the outside chance that our method manages to succeed, 
  //  clear any lingering error "growls".
  $.unblockUI();
}

Since it’s important that the user notice the error message, we can specify a much longer than default timeout for the “growl”. Twenty seconds in the example above.

The success handler is added to make sure any leftover error is cleared after a successful request completes. This avoids any confusion that would be caused by an error message remaining even after a successful request completes.

Because $.growlUI() is just a shortcut for a complex BlockUI usage, $.unblockUI() works on “growl” messages just as if they were $.blockUI() modals.

Note: As with the rest of BlockUI, these “growl” messages can be customized via CSS. For this simple demo, I’m happy with the default styling, but you can easily change it to match your application.

Conclusion

You should never assume your service calls are 100% reliable. This seems obvious, but I’ve encountered mountains of production code without error handling.

As you’ve hopefully seen in this post, it is trivially easy to add great looking error handling to your jQuery service calls. After all is said and done, you’re only looking at about 3-5 extra lines of code. This substantial improvement in usability is well worth the minimal effort.

We focused on an example of using a page method here, but keep in mind that this technique can be implemented to work with both page methods and web service calls.

Source

Download source: jquery-error-handling.zip

###

Originally posted at Encosia. If you’re reading this elsewhere, come on over and see the original.

Use jQuery to catch and display ASP.NET AJAX service errors

A breaking change between versions of ASP.NET AJAX

When working directly with JSON serialized ASMX services, be it via jQuery, pure XmlHttpRequest calls, or anything else other than the ScriptManager, one question inevitably arises. That question is of the inexplicable .d attribute that appeared in ASP.NET 3.5.

What is it? Why is it there?

In this post, I’ll use both a 2.0 and a 3.5 example ASMX web service to illustrate exactly what’s going on. I’ll also show you why it’s a good change.

An example

Following a concrete example always helps to better clarify these things. For that purpose, let’s assume that we want to call a web service and retrieve an instance of the following Person class:

public class Person
{
  public string FirstName;
  public string LastName;
}

The ASMX web service to return an instance of that class could be simple as this:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public Person GetPerson()
  {
    Person p = new Person();
 
    p.FirstName = "Dave";
    p.LastName = "Ward";
 
    return p;
  }
}

Because our WebService class is decorated with the [ScriptService] attribute, the ASP.NET AJAX Extensions (System.Web.Extensions) will automatically serialize the return value as JSON if properly requested.

Note: A common anti-pattern that I’ve seen in practice is using a return type of string and returning a manually JSON serialized object. Don’t. It’s unnecessary and results in doubled effort on both the server and in the browser.

Let the framework handle this task unless you have a good reason not to use the built-in functionality. It works just fine in most scenarios.

Calling the service and inspecting its result

Using jQuery to consume an ASMX web service is simple, but does require jumping through a few hoops. We can use this jQuery to consume the Person service we just created:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/GetPerson",
  data: "{}",
  dataType: "json",
  success: function(msg) {
    // Do interesting things here.
  }
});

Making that call against an ASP.NET 2.0 site with the ASP.NET AJAX Extensions 1.0 installed, this JSON object would be the return value:

2.0 JSON Response in Firebug

I find that it often helps to visualize the JSON in a more human readable format. This is the same JSON object as seen in the Firebug screenshot above:

{"__type"    : "Person",
 "FirstName" : "Dave",
 "LastName"  : "Ward"}

Within the success callback shown above, you may access properties of the Person exactly as you would expect. For example, msg.FirstName will evaluate to “Dave”.

Waiter, there’s a .d in my msg soup!

Eventually, you’ll finally convince management to let you upgrade the site to ASP.NET 3.5. After all, you can use an object initializer to cut the size of the web service in half!

However, your msg.FirstName statement now results in the dreaded undefined.

What happened? Let’s inspect the ASP.NET 3.5 response in Firebug:

3.5 JSON Response in Firebug

The entire Person object is wrapped within a new “d” object now. Alternatively we might visualize it this way:

{"d":{"__type"    : "Person",
      "FirstName" : "Dave",
      "LastName"  : "Ward"}}

As you’ve probably figured out by now, the solution is to reference the property as msg.d.FirstName now. In our example, this will again resolve correctly as “Dave”.

This is the case with all ASMX services JSON serialized through the ASP.NET AJAX Extensions in ASP.NET 3.5. Even if you’re only returning a scalar return value, such as a string, int, or boolean, the result will always be enclosed within the “d”.

Why did it change?

While I wish this unexpected change had been more clearly announced, it’s a good one. Here’s how Dave Reed explained it to me:

{"d": 1 }

 

Is not a valid JavaScript statement, where as this:

 

[1]

 

Is.

 

So the wrapping of the "d" parameter prevents direct execution of the string as script. No Object or Array constructor worries.

[] is JavaScript’s array literal notation, allowing you to instantiate an array without explicitly calling a constructor. To expand on Dave’s explanation, simply consider this code:

["Dave", alert("Do Evil"), "Ward"]

That literal array declaration will execute the alert in most browsers. Danger!

Update: For an even better description of why the .d is important, from Dave Reed himself, be sure to see his comment below.

Conclusion

I hope this post has helped clarify any confusion caused by the “d” in ASP.NET 3.5’s JSON serialized ASMX services, and made you aware of why it’s worth the hassle. As sophisticated as XSS exploits have become in recent years, unexpected script execution has the potential for devastating consequences. That extra “d” is well worth the short-term hassle.

Microsoft often catches flak over security related issues, but rarely gets credit when they do things right. I, for one, think the ASP.NET team deserves credit for remaining vigilant and often preempting these exploits for us.

Thanks, guys.

###

Originally posted at Encosia. If you’re reading this elsewhere, come on over and see the original.

A breaking change between versions of ASP.NET AJAX

WP Like Button Plugin by Free WordPress Templates