jQuery and Ajax Error Handling

Website development duties were once assigned to different individuals with two distinct roles: A designer focused on the all matters related to the front-end HTML and CSS, and a developer was responsible for the server-side code. JavaScript’s meteoric rise to first-class citizen status has blurred these traditional lines, forcing developers into what was once considered taboo territory. The results have been spectacular, with frameworks such as jQuery significantly streamlining JavaScript’s often unwieldy native syntax, and programming techniques such as Ajax bringing highly responsive user interfaces to the browser. The marrying of jQuery and Ajax has been particularly impactful, providing developers with a powerful solution to the problem of asynchronously interacting with and updating parts of a web page.

Despite all of jQuery’s strengths, incorporating Ajax-driven features into web applications can be a frustrating endeavor, due in large part to the challenges of determining where exactly in the process things go awry. Did an error occur in the browser? What about during the transmission of data between client and server? Or perhaps within the server-side code? These are all possibilities developers need to consider when problems arise.

If you struggle with diagnosing and resolving Ajax errors, try these error detection and resolution techniques and technologies.

Native jQuery Error Detection

The vast majority of Ajax-related errors will come as a result of malformed JSON or server-side issues that generate a 404 (not found) or 500 (internal server error) response code. Despite this fact, you’ll often encounter code like this:

$(document).ready(function () {

  $.ajax({
    url: 'http://localhost/api/products/list',
    type: 'GET',
    dataType: 'json',
    success: function() {
      // Receive and format data
    }
  });

});

This snippet performs a straightforward Ajax GET request, contacting a URL and expecting the returned data to be formatted using JSON. Yet upon execution, suppose the returned data isn’t output to the browser as dictated by the success callback, leaving one wondering what caused the problem. A glance at Firefox’s error console doesn’t indicate any JavaScript syntax errors, and you’ve already thoroughly tested the server-side script’s JSON output. So what’s the problem?

As it turns out, the problem could be that the script is simply pointing to a nonexistent server resource, producing a 404 error rather than the desired output. Fortunately, error detection is easy to integrate thanks to the statusCode setting:

$.ajax({
  url: 'http://localhost/api/products/list.php',
  type: 'GET',
  dataType: 'json',
  statusCode: {
    404: function() {
      $("#response").html('Could not contact server.');
    }
  },
  success: function() {
    // Receive and format data
  }
});

You can detect and handle additional server status codes as well simply by following the same pattern:

statusCode: {
  404: function() {
    $("#response").html('Could not contact server.');
  },
  500: function() {
    $("#response").html('A server-side error has occurred.');
  }
},

Detecting Data Errors

With commonplace 404 and 500 errors handled, it makes sense to next account for errors that occur due to malformed JSON formatting. Suppose the aforementioned http://localhost/api/products/list.php URL does indeed exist, and is intended to return a list of products formatted using JSON. A properly functioning PHP script (although simplified for the purposes of this tutorial) might look like this:

<?php

  $products[] = array (
    array (
      "name"         => "Stylish Wallet",
      "price"        => "12.99",
      "manufacturer" => "European Limited"
    ),
    array (
      "name"         => "Pleather Shoes",
      "price"        => "37.99",
      "manufacturer" => "Hungarian Imports"
    )
  );

  echo json_encode($products);

?>

But suppose that in the API developer’s haste he accidentally erased the <?php delimiter, causing the entire PHP script to be returned to the client rather than just the desired JSON payload. As with the previous example, lack of proper error handling logic would make this problem difficult to detect, particularly if you aren’t privy to the inner workings of the server-side API. One easy way to account for such unexpected errors is through the error callback:

$.ajax({
  url: 'http://localhost/openlogic/list.php',
  type: 'GET',
  dataType: 'json',
  statusCode: {
    404: function() {
      $("#response").html('Could not contact server.');
    },
    500: function() {
      $("#response").html('A server-side error has occurred.');
    }
  },
  error: function() {
    $("#response").html('A problem has occurred.');
  },
  success: function() {
    $("#response").html('Success!');
  },
});

Reviewing Network Traffic and JSON with the Firebug Console

In addition to these programming techniques, a useful tool that can provide developers with keen insight into the HTML, CSS, JavaScript, and network activity associated with a web page is the Firebug Firefox extension. One particularly useful feature is its ability to monitor both outbound and inbound requests, including the request and response headers and payload. This capability can be indispensable for providing quick answers to the questions we posed earlier in this article, because you can peer right into the behavior and characteristics of each leg of the Ajax request/response process.

After installing Firebug, you have access to a new console window that allows you to examine all the requests that occurred in the process of loading a web page, as depicted in Figure 1.

Viewing all requests associated with a web page

Clicking on the Headers tab provides information about the nature of the request, as shown in Figure 2.

Learning more about the nature of the Ajax request

Clicking on the Response tab provides more information about the associated response, including the JSON payload, as depicted in Figure 3.

Peering into a JSON-based response payload

This ability to examine each component of the request without having to resort to littering the code with debugging statements is invaluable, and something you’ll use on a regular basis when developing Ajax-based features.

Advertisements

About hackmyass
free the internet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: