provides software and services that enable enterprises
Live Chat 1-888-673-6564

Open Source Software Technical Articles

  • Home
  • Search
  • Contact Us
  • Products and Support
  • Services
  • Enterprise OSS Blog
  • Wazi Technical Blog
  • About Wazi
  • Attributions and Licensing
  • Supply Chain Compliance
  • How to Contribute
  • Contributors
  • Resources Library
  • Cloud Services
  • Partners
  • Customers
  • Community
  • Company
  • Careers
  • News and Events

Subscribe to Wazi by Email

Your email:


Enterprise Developer Support 24 x 7, Get a Support Quote Now!


click-here-to-chat-with-an-online-representative

download-oss-discovery

Latest Posts

  • A more colorful LibreOffice unveiled
  • Toward a more colorful LibreOffice
  • Flexible administration with Puppet's Facter and templates
  • Knock for OpenSSH
  • Get more out of phpMyAdmin
  • Image annotation in GIMP, Dia, and OpenOffice Draw
  • Solr, Drupal 7, and faceted search
  • Using FreeNAS' new full disk encryption for ZFS
  • Create distributed storage with Gluster
  • How to set up Solr 4.2 on Drupal 7 with Apache

Connect with Us!

Current Articles | RSS Feed RSS Feed

jQuery and Ajax Error Detection and Handling

Posted by W. Jason Gilmore on Thu, Oct 27, 2011
  
Email This Email Article  
Tweet  
  

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!');
},
});

19a98812-f823-48dc-841e-bf029c63c6d7

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.



[caption id="attachment_91492" align="alignnone" width="590" caption="Viewing all requests associated with a web page"][/caption]

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



[caption id="attachment_91493" align="alignnone" width="590" caption="Learning more about the nature of the Ajax request"][/caption]

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



[caption id="attachment_91494" align="alignnone" width="590" caption="Peering into a JSON-based response payload"][/caption]

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.



Conclusion


Newcomers to Ajax-driven web development can be intimidated by the often opaque nature of the request and response process, particularly when errors begin to crop up. Fortunately, you can easily add error detection and handling features to your future projects. Are you using other approaches to managing Ajax-oriented errors than the ones we talked about here? Tell us about them in the comments!

Follow @openlogic
Follow @CloudSwing

This work is licensed under a Creative Commons Attribution 3.0 Unported License
Creative Commons License.Follow @openlogic
Follow @OSCloudServices

This work is licensed under a Creative Commons Attribution 3.0 Unported License
Creative Commons License.
Tags: Technical, Tips & Tricks, Firebug, Programming, jQuery

Comments

asdasdaasd
Posted @ Monday, April 29, 2013 5:16 AM by sadas
Post Comment
Name
 *
Email
 *
Website (optional)
Comment
 *

Allowed tags: <a> link, <b> bold, <i> italics

Loading...
Error sending email
Email sent successfully

Email article
Email To : 
Your name : 
Message : (maximum 200 characters)
Home | Search | Contact Us | Products and Support | Services | Enterprise OSS Blog | Wazi Technical Blog | Resources Library | Cloud Services | Partners | Customers | Community | Company | Careers | News and Events
Products
OpenLogic Exchange (OLEX)
License Compliance Module
OSS Discovery
OSS Deep Discovery
OpenUpdate
Services
Open Source Support
CentOS Support
Scanning & Compliance
Open Source Training
Professional Services
Solutions
Support & Indemnification
Open Source Governance
Open Source Scanning
Open Source Provisioning
Consulting & Training
Contact Us
1-888-673-6564


© 2013 OpenLogic, Inc. All rights reserved.
Site Map  |  Privacy Policy