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');

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.

Related Posts