zen of coding

Two ways to debug your AJAX queries

Every once in a while you might have a need to trigger an AJAX action in the controller, which should return some results from the server…

When everything works, well it is certainly all fine and dandy, but if things go haywire, first thing to check out is the response given by the server… and more importantly why does it not match your expectations. One of the more typical questions is: “What query was executed on the DB, during the AJAX call”?…
Because AJAX calls are not easily logged to any console, sometimes it becomes a little troublesome to figure out.

When using CakePHP you have two methods to see what’s happening on the DB level.

1. If you use debug kit

There is one little known, but nice feature.
After you load the page, which executes some AJAX request… do the following:
1. Click the “History” tab
2. In the list you should see the given AJAX call to some controller action
3. Click it
4. Switch over the to the SQL log tab and see what has happened.
(The background of the queries should be mild green, which will signify that you are looking at a previous request in the “history” of calls)

… amazing feature indeed. Yet, unfortunately, it doesn’t work 100% of the time. (I wish I had a more in-depth answer as to why).

2. Do not despair, there is another way to log your SQL dealings with a few lines of code.

Using the same scenario as above, in your action which is being triggered by AJAX from the client, add the following snippet:

$db = ConnectionManager::getDataSource('default');
debug($db->getLog());

Now, if you are using firebug (or similar tool, which I hope you certainly do)… You’ll see the exact query and some other debug info generated by the cake’s DB drivers.

p.s. Thanks to jrbasso, for this wonderful and helpful hint.

  • Pingback: Tweets that mention Two ways to debug your AJAX queries | nuts and bolts of cakephp -- Topsy.com()

  • RSK

    @teknoid : My web page have a ajax request on the on change event of the select box to fill the second select. the debug kit is installed and ok. But the History tab is empty and can’t find the “explain query button” on sql query tab. What may be the issue?

  • teknoid

    @RSK

    DebugKit is flaky, I don’t know why it works sometimes and does not at others.
    Another option is to install FirePHP it should give you the DebugKit output in the console for each AJAX request.

  • RSK

    @teknoid : thankz for your time.I got it worlking. I enabled the cache and now it showing the requests.

    CakePHP + Firefox + Firebug + FirePHP + CakePHP-DebugKit + FireCake
    make life more easier.

    thankz again for your valuable tipz.looking forward for more such tipz ;)

%d bloggers like this: