Techniques

Essential Tips and Tricks for Coding and Debugging AJAX Based Website

Written by Kevin Liew on 07 Dec 2009
34,830 Views • Shares
10 comments

Introduction

AJAX is a wonderful piece of technique that has changed the way website response to user input. I like AJAX a lot, I discovered the goodness of AJAX 2 years ago, but the development was quite hard without jQuery framework. As a result, I didn't really keen to use it back then. Now, I'm with jQuery, and jQuery has made it's so much easier to integrate AJAX into a website.

I assume you all have experiences with AJAX. As a AJAX lover, I found it can be quite hard to debug, especially debugging other developers code. It's because of too many technologies are involved in this technique - CSS, Javascript and PHP. So, I created this article and to share what I have learnt to all of you.

A little bit of AJAX

AJAX is abbrieviated from Asynchrounous javascript and XML. It's not a new technology, but the implementation of a group of technologies to achieve a seamless interaction between client and server.

Typically, xhtml and css present the information to user and javascript is used to handle user interactions, and a server side language is to perform users' requests and might return result back to the user. It's all happening in the background using the Javascript XMLHttpRequest. Javascript plays a main role to tie all these technologies together and create the asynchronous interaction between client ans server.

How AJAX Works

Advantages:

  • Reduce connections and bandwidth to the server, images, scripts, stylesheets only need to be downloaded once
  • Reduce loading times. User doesn't have to load pages again and again, it all happens in a same page!
  • Increase responsiveness and end user experiences.

Usability Guidelines:

  • Always provide feedback to user. Let user knows the server is processing the request. We can indicate that by displaying a relevant message or loading icon.
  • Prepare a plan to those users without Javascript support.

Test the server side script

A lot of times, it's the server script (php, asp.....) that causing the problems. I'm a PHP developer, everytime before I plug it into the AJAX, I would do some testing by passing parameter in the URL first to make sure it generate desired result.

We will not go through too much of the debugging skills because the best way to learn it is to figure it out by yourself, however I will introduce some of the basic tools and codes that could help you to reduce human errors and syntax errors.

  • Use a proper editor with syntax highlighting feature.

    If you're still doing your coding with a normal notepad just like I did few years ago, you should change your editor now. :P. Syntax higlighting feature is a very useful to help you identified spelling error, missing quotes, wrong command and make your code more easy to read. For mac and window users, I recommend:
    • Notepad++ - I reckon this is the best free editor, but unfortunately it doesn't available in Mac, is the only software I missed so much after I switched to mac :(. Notepad++
    • Smultron & Textwrangler - I'm using smultron, but the owner doesn't support it anymore and I found that the syntaxhighlight is a bit buggy when you are using multiple languages for example, javascript, html, css and php. :( TextWrangler probably the most famous free editor at the moment. Smultron and Textwrangler
    • TextMate & Coda - Both of these editors are not free. Coda is an all-in-one kind of editors that come with built-in ftp, svn, css, terminal, books and more. I don't really like the all-in-one concept because if one of the built-in functionality crashed, you will have to terminate the whole program and relaunch everything, it's like Single-Point-of-Failure, and it's irritating to keep switching tabs as well. For TextMate, it's a really powerful editor, heaps of features that will reduce your debugging efforts. If you have your money, get TextMate :) textmate
  • Print out variables, data content

    Just based on my own debugging experiences, always print out the content if something went wrong to make sure you have the correct data store in it. I'm a php developer, not very sure about other server side language, but I guess they are almost the same. With PHP, uou can use:
    //Sample data - array
    $data = array('apple', 'orange', 'durian');
    
    var_dump($data);
    
    //or
    
    print_r($data);
    
    //but normally I would create a function like this:
    function dump($data) {
    	echo '<pre style="background:#fff; text-align:left">';
    	var_dump($data);
    	echo'</pre>';
    }
    
  • Test the parameters

    With AJAX, we can using either GET or POST to send data to the server side script. Luckily, we can test the server side script easily just using a simple if else statement.
    //Assume this AJAX script test.php will call by Javascript using POST method, 
    //but it will be easier to test it with GET method.
    $name = ($_POST['name'] ? $_POST['name'] : $_GET['name']);
    $email = ($_POST['name'] ? $_POST['name'] : $_GET['name']); 
    
    echo $name;
    echo $mail;
    

    Refer the code above, we will able to pass parameters by using the following URL:

    http://www.someurl.com/test.php?name=Kevin@email=Kevin@someurl.com

    Yep, with just simple switching, you will able to test the functionality of your server side script.

Test the Javascript

This one is a bit tricky, because I found that different browsers have different way to read javascript. For example, firefox is more forgiveful, if you forget to put semicolon in some lines, the script will still work as long as it's on separate line. But for Internet explorer, that's not the case. It will display an annoying yellow icon on the status bar.

However, I do have some tools and tips on my hand to assist me:

  • Get Firefox!

    I'm not biased, but firefox is a good stuff for web designers and developers because of its large pool of extensions. Most importantly, its behaviour is predictable, more standard compliant and won't give us too much of website rendering problem. However, its rendering engine can be too forgiveful sometimes that even if you made some code errors, it will still display the result you want, but in other browsers, they don't. Check out these articles for the best extensions you need:
  • Web Development Tools

    Use web development tools like firebug, firequery or online javascript validation tools. If you read the article about firefox extension above, they are being mentioned everywhere! It's important to debug javascript because you need to get as much of information as possible that will tell you what's wrong and what's going wrong.
  • Right Parameters

    Make sure you're passing the right parameters to the URL. You can check it using alert() to display the data or declare an ID called #debug and print it out using jQuery $(). The main purpose is to print out the output

    Consider the following scenario, if your AJAX doesn't work, you can always check and make sure the data is correct by using this method:

    var param = 'name=' . $('input#name').val() . '&email='  + $('input#email').val();
    
    //use this to ensure data is well-formed
    alert(param);
    
    //or assume you have <p id="debug"> declared in the html doc
    $('#debug').html(param);
    
    $.ajax({
    	type: "GET",
    	url: "test.php",
    	data: param,
    	cache: false,
    	success: function (html) {
    		$('#result').append(html);
    	}
    });	
    
  • Correct URL Structure

    A lot of times, I missed the ampersand or put the ampersand in an incorrect position.

    Two common mistakes:

    //forgotten to put question mark
    http://www.somedomain.com/save.php&name=kevin&email=test@test.com
    
    //forgotten to put ampersand in between name's data and email parameter
    http://www.somedomain.com/save.php?&name=kevinemail=test@test.com
    
  • Check Returned Data

    This is to make sure the server side script returns correct data. Wit this method, it can help you to debug the server side script as well. If the server side script has error in it, the javascript will return the error message generated by the server side script.
    var param = 'name=' . $('input#name').val() . '&email='  + $('input#email').val();
    
    $.ajax({
    	type: "GET",
    	url: "test.php",
    	data: param,
    	cache: false,
    	success: function (html) {
    		alert(html);
    	}
    });	
    

Final words

Debugging code is a time consuming process and it's a good practice to keep on testing it from the beginning. You do not want to write large amount of code and test it later. It will only make the debugging process harder. I hope my techniques will able to help you, and if you have any better ways to test it, do let me know :). Thanks.

Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

10 comments
Calaelen 7 years ago
I am using dBug for all debugging outputs.
http://dbug.ospinto.com/

Very easy to use and helps a lot :)
Reply
xamox 7 years ago
I recommend jEdit as the best text editor. It is open source, cross platform, and has a ridiculous amount of plugins all for free.
Reply
Maarten Keirsebilck 7 years ago
Aptana is also a great, free IDE for writing Javascript, HTML, CSS and PHP.

They also offer plugins for Ruby on Rails, and Adobe AIR.

It\'s downloadable at www.aptana.com
Reply
Walter Wimberly 7 years ago
I personally like Aptana (http://www.aptana.com/) as a code editor. (color coding, code completion, an understanding for several AJAX libraries, and debugging tools built in, plus an understanding of PHP and Rails)
Reply
Olivier 7 years ago
You made a little mistake in replacing & by @ in :
http://www.someurl.com/test.php?name=Kevin@email=Kevin@someurl.com
Reply
seo 7 years ago
thanx for examples...
Reply
kametgida 6 years ago
eyw.
Reply
kamert 6 years ago
eyw.
Reply
sooraj 5 years ago
Hi,
If you want to debug anything in Ajax, use firebug its super easy...no headaches..at all...in firebug, under console, you can see your send parameters, the generated page and the resultant reply back to your calling function.....
Reply
fikadu 5 years ago
nice
Reply