JavaScript error logging in X-Cart
X-Cart shopping cart has got powerful tools for PHP and MySQL error logging. However nowadays it is even more important to track JavaScript errors. Usually a store owner just does not see such errors until he gets calls from disappointed customers. It is not wise to lose customers and orders due to such errors, especially since there is a simple solution.
Actually, it is pretty easy to add JavaScript error log. Firstly we need to add a small JavaScript that should be inserted to all the store pages, thus it should be inserted into the skin1/customer/home.tpl.
<script type="text/javascript"> {literal} window.onerror=function(msg, file_loc, line_num) { jQuery.get(xcart_web_dir+'/errors.php', {'msg': msg, 'file_loc': file_loc, 'line_num': line_num, 'curl': window.location.href}); } {/literal} </script>
This script has to be included into the <head> section of the page. And the script would better be the first one in the row after the <head> tag, otherwise it just won't track execution of the scripts above it.
In this script we are using the JQuery lib, thus you should include it in old X-Cart versions. It can be done in the following way:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
But it's better to download the library directly to your server and include it from the server (just specify the right url in the code above).
Ok, back to the onerror head script. As you can see, the “errors.php” is executed here by the ajax request. So, let's create it in X-Cart root directory.
<?php include "auth.php"; x_log_add('DEBUG', 'Javascript error: '.$curl."\nmessage:".$msg."\nfile:".$file_loc."line:".$line_num, false); exit;
That's all. Now we can track JavaScript errors in the admin area logs (admin/log.php), information will be written to the “Debug messages” section and will look like:
[08-Jun-2011 10:01:11] (shop: 08-Jun-2011 10:01:11) DEBUG message: Javascript error: <your store> message:unterminated string literal file: <js file where the errors occurs> line:970 Request URI: /errors.php?msg=unterminated+string+literal&file_loc=http%3A%2F%2Fwww.gemaffair.com%2F&line_num=970&curl=http%3A%2F%2Fwww.gemaffair.com%2F
That is all we need to trace the problem and fix it.