Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryStatistics and Tracking

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Logging With JavaScript

Variable values and other events in JavaScript code can be logged in a file located on the server.

The way it works is that JavaScript sends a notice to a PHP script on the server (via Ajax). The PHP script updates the log.

Such functionality comes in handy when developing JavaScript, especially in situations where alert() function notices would change the program flow.

I had occasion to use this very code last week while developing an image upload system. The image is uploaded via Ajax, stored on the server, its URL posted into the correct MySQL record of product details, and the uploaded image displayed on the dashboard page.

The process needed special handling when an image is uploaded and no product record had previously been created. And the special handling is where I needed help in knowing what the code was doing. (It was doing things different than I had expected.)

Because it was Ajax, and the way it was coded, any alert() lines would send the browser to a blank page.

Clearly, I needed an information dump that did not interfere with the JavaScript flow.

I had made other similar dumps before. So this one took only a few minutes.

Then I thought you might be interested in using it too.

The software was tweaked to make it more user friendly. And it comes with today's article.

Let's do the PHP script first. It will need to be on the server ready to update the log file on demand. Here is the source code.

<?php
/* JavaScript Event Logger
   Version 1.0
   May 5, 2021
   Will Bontrager Software LLC
   https://www.willmaster.com/
*/
date_default_timezone_set('UTC'); // Change time zone designation if desired.
if( isset($_POST['file_name']) and isset($_POST['log_content']) )
{
   file_put_contents($_POST['file_name'],date('r')."\n{$_POST['log_content']}\n\n",FILE_APPEND);
}
exit;
?>

There are no required customizations. But if you wish to change the time zone designation from UTC (Universal Time, also known as GMT), you may. The designation for your preferred time zone can be obtained at the Timezone Designations for PHP Software page.

Upload the PHP script to your server as JSeventLogger.php or other *.php file name that you might prefer. The URL of JSeventLogger.php will be specified in the JavaScript.

Because JSeventLogger.php is triggered by Ajax with asynchronous connections, the order of content received for logging might not be the order they were sent from the JavaScript. It can happen with nearly simultaneous Ajax use that an Ajax request succeeds in getting a connection to the server before the immediately previous Ajax request does.

When JSeventLogger.php logs a JavaScript request, it first publishes the date and time. On the next line, the content sent by the JavaScript is published. Because some of the content to publish may be large and/or multi-line, JSeventLogger.php inserts a blank line between the date/time line and the previously published content.

When JSeventLogger.php is uploaded and you have made a note of its URL, it is ready to be used with your JavaScript.

Below is the JavaScript.

The AppendInfoToExternalFile() function is required on all pages that have JavaScript events to log.

<script style="text/javascript">
function AppendInfoToExternalFile(filename,filecontent)
{
   var url = "/logger/JSeventLogger.php"; // URL of the PHP Event Logger.
   var http = new XMLHttpRequest();
   if(! http) { alert('No internet connection for logging.'); return; }
   var params = new Array();
   params.push( encodeURIComponent("file_name") + "=" + encodeURIComponent(filename) );
   params.push( encodeURIComponent("log_content") + "=" + encodeURIComponent(filecontent) );
   http.open("POST",url,true);
   http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http.send(params.join("&"));
}
</script>

AppendInfoToExternalFile() has one customization.

Replace /logger/JSeventLogger.php with the relative URL to JSeventLogger.php. The URL should be relative to document root (the absolute URL to the script minus the leading http(s):// and domain name). As an example, absolute URL https://example.com/script.php becomes relative URL /script.php.

When that customization is done, AppendInfoToExternalFile() is ready to be used on any of your web pages. JavaScript on your web page can call AppendInfoToExternalFile() with information and it gets logged on the server.

To use the AppendInfoToExternalFile() function, calling it requires two items of information, the log file location and the content to log.

  1. The log file location may be the file name only, in which case the file is updated in the directory where JSeventLogger.php is installed. Or the location may include a directory designation with the name.

    In each of the example calls to AppendInfoToExternalFile(), the file location is "log.txt".

  2. The content can be any text you want logged. Generally, the content would contain the value of variables, but may also contain anything else that can be provided with JavaScript.

In this first example, the content to log is the value of the me variable.

var me = "Will";
AppendInfoToExternalFile("log.txt",me);

The variable me will supply the value of the variable.

The second example specifies two lines of content for logging (a line break is specified with \n). The first line is a narrative and the value of the you variable. The second line is a narrative and the length of the value.

var you = "Your Name Here";
AppendInfoToExternalFile("log.txt","Your name is recorded as '" + you + "'.\nThe length of your name is " + you.length + " characters (including any spaces).");

Some scrolling will be needed to see the illustrative example. The content for AppendInfoToExternalFile() is all one line.

The third example content is a line with a narrative and total of two variable values added together.

var pile1 = 10;
var pile2 = 17;
AppendInfoToExternalFile("log.txt","The total in both piles is " + parseInt(pile1+pile2) );

When those three are logged, the content of the log file on the server looks something like this:

Sun, 09 May 2021 15:22:03 +0000
Will

Sun, 09 May 2021 15:22:03 +0000
Your name is recorded as 'Your Name Here'.
The length of your name is 14 characters (including any spaces).

Sun, 09 May 2021 15:22:03 +0000
The total in both piles is 27

Wherever you want your JavaScript to log information, call the AppendInfoToExternalFile() function with the log file name and the content to be logged.

To test, put the web page's URL into your browser. Note that the web page needs to be accessed with a browser and with a http://... or https://... URL for Ajax to work. Ajax is functional only on the internet.

To reiterate, when the AppendInfoToExternalFile() function is in the page, it can be called at any point in other JavaScript to log whatever you need to know about that point.

(This article first appeared with an issue of the Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC