A common type of question I find on Stack Overflow are beginners having trouble with figuring out why their AJAX application / functionality isn’t working. They usually go something like this…
I have two input boxes which accept the username and password and sends it to the PHP login page via AJAX. But when I type in my credentials, I don’t get logged in. Why isn’t it working?
When starting out to fix a problem, you need to first find out what the problem is. To do that you need to isolate where the problem lies, so break it down into its individual components. In no particular order, these would be
- The Javascript and AJAX
- The PHP and server side code
- The DOM and HTML
The Javascript
The PHP and Server Side Code
When you work with AJAX, it helps if you make sure that your application works without AJAX initially. This serves the double purpose of making sure your core functionality works and having a fallback when Javascript is disabled. Assuming you’re working with GET and not POST, either copy the request URL from Firebug or craft your own and access it in the browser. If you get an error then you’ve isolated (one of) your problem(s)! Find out what’s wrong and fix it and then see if the AJAX functionality works.
Using an IDE when coding gives you many benefits. Although you may think that notepad might be enough for your needs, something like Eclipse (which I use) or NetBeans (which I’ve used) can come in very handy to catch some problems as you code them.
And don’t forget to have a debugger setup. I mainly use Xdebug, but you can just as easily use ZendDebug.
Once you make sure you have the JS async call working properly with the serverside PHP script, you can look at the callback and the DOM.
The DOM and HTML
The most common reason for AJAX updates not working on the client side is usually because the element you are trying to update doesn’t exist. Confirm that the element exists first. I usually use the .length property or the toggle() method to make sure I have the correct reference.
And for any event issues, make sure that the DOM element exists before you bind any events to it. A related cause is when you bind an event with an element but then update the element in thee DOM so you lose the reference. An easy solution to avoid this problem is to use something like the .delegate() method if you’re using jQuery.
To sum it up, whenever you run into a problem carry out the following steps.
1. Isolate the problem
2. Focus on the problem area
3. Fix the bug (easy part!)
