Register now or login here to start promoting your blog and your favourite articles.
Essential Tips and Tricks for Coding and Debugging AJAX Based Website
7 Dec 2009 - 9 Comments
AJAX combined different web technologies to work together, as a result, it would a major headache to debug it if problems arised. I have a few tips and tricks that I learnt from my journey of ajax web development.
Author: kevin | Source: queness

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.

Copyright & Usage

The effects and techniques demonstrated in tutorials on Queness can be used in whatever manner you wish without attribution. You cannot copy whole tutorials (unless permission is given), either in English or translated to another language.

Share This Post to Support Me! :)


Comments

kamert on 10 Jul 2010 says:
eyw.
kametgida on 10 Jul 2010 says:
eyw.
seo on 6 Jan 2010 says:
thanx for examples...
Walter Wimberly on 10 Dec 2009 says:
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)
Olivier on 10 Dec 2009 says:
You made a little mistake in replacing & by @ in :
http://www.someurl.com/test.php?name=Kevin@email=Kevin@someurl.com
Maarten Keirsebilck on 9 Dec 2009 says:
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.

Its downloadable at www.aptana.com
xamox on 8 Dec 2009 says:
I recommend jEdit as the best text editor. It is open source, cross platform, and has a ridiculous amount of plugins all for free.
Calaelen on 8 Dec 2009 says:
I am using dBug for all debugging outputs.
http://dbug.ospinto.com/

Very easy to use and helps a lot :)
  • Page :
  • 1


Leave a comment

Subscribe RSS Subscribe RSS, Keep yourself updated with queness latest posts!
Pixel Crayons

Buy wholesale computers directly from China at DHgate.com

Discover the tools to build your e-Commerce Site with Netfirms

Buy China Products from Made-in-China.com

Cocktail Dresses

SmartPhone Cell Phone

Wholesale electronics

Web Hosting Rating

Buy WOW Gold

Get your cdl today

Debt collector review

  •  
  •  
  •  
  •  
  •  

Community News

Recent Comments

Random Posts


View all posts and news Back to top

About the Author

A web designer and developer who is passionate and keen on contributing to the web development industry. Feel free to say hi to me, or follow me on twitter.

Kevin Liew