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

WillMaster > LibraryMarketing With Software

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!

Event-Triggered Email

On a few web pages, it may be desirable to know immediately if someone takes a certain action on the page.

Examples where you may want immediate notification are product sales pages and information pages for paid ad responses.

When certain events happen at the web page, you are sent an email. Examples of events are:

  • The page has loaded.

  • The page is scrolled.

  • An image is tapped.

  • A form is submitted.

  • The page is viewed longer than a specified amount of time.

The system is for website owners and maintainers who need to stay on top of certain pages, perhaps during a special promotion.

  • A high percentage of page loads that report a page scroll could mean the content is at least somewhat interesting.

  • Staying on the page a long time could mean they are reading the whole thing.

  • A low percentage of form submissions might mean the message isn't quite doing the job of getting your preferred action taken.

This system is not for every web page, only for pages where it is needed. Otherwise, you could be inundated with email more than necessary.

How it Works

It is simple in concept. It even works on WordPress posts and pages.

  1. When a specific event happens, Ajax sends event information to a PHP script.

  2. The PHP script sends the email to you with the event information.

Because Ajax is JavaScript, no email is sent for browsers that have JavaScript suppressed or turned off. (Further, virtually all bots don't run JavaScript.)

Implementation

We'll do implementation this way.

  1. Install the PHP script. Customizations are the email address and subject line for the outgoing email.

  2. Put the Ajax on the page. The customization is specifying the URL of the PHP script.

  3. Code to make certain events notify the Ajax.

When a specific event happens, Ajax is notified. Ajax sends info to the PHP script. The PHP script sends an email with the info.

Installing the PHP Script

Below is the PHP script, followed with customization notes.

Make the customizations. Then upload the script to your server as EventMail.php or other *.php file name you prefer. Make a note of its URL. (The instructions on this page assume EventMail.php for the PHP script file name.)

<?php
/* 
   Event Email Sender
   Version 1.0
   July 25, 2020

   Will Bontrager Software LLC
   https://www.willmaster.com/
*/

/* Customization */
// There are 2 places to custmoze.

// Place 1 --
// The address for sending the email to.

$EmailAddress = "name@example.com";

// Place 1 --
// The subject line for the email.

$EmailSubject = "Ajax Event Email";

/* End of customization */

if( empty($_POST['url'])  or 
    empty($_POST['info']) or 
    empty($_POST['ip'])   or 
    empty($_POST['ua']) ) { exit; }
$content = array();
$content[] = 'This email sent from script ' . $_SERVER['PHP_SELF'];
$content[] = "Ajax location: {$_POST['url']}";
$content[] = 'Info from Ajax: ' . str_replace("\r\n","\n",$_POST['info']);
$content[] = "User IP address: {$_POST['ip']}";
$content[] = "Browser identity: {$_POST['ua']}";
$header = array();
$header[] = "From: $EmailAddress";
$header[] = 'Content-type: text/plain; charset="utf-8"';
$header[] = 'MIME-Version: 1.0';
mail($EmailAddress,$EmailSubject,implode("\n\n",$content),implode("\n",$header));
?>

Customization notes —

EventMail.php has two places to customize.

  1. Email address —

    The $EmailAddress variable has the name@example.com value. Replace name@example.com with the correct email address to send the information to.

  2. Email subject —

    The $EmailSubject variable has the Ajax Event Email value. If you prefer a different subject line, replace Ajax Event Email.

EventMail.php is now ready to upload to your server. Make a note of its URL.

FYI, the email that EventMail.php sends looks something like this:

This email sent from script /php/EventMail.php

Ajax location: https://example.com/special-page.php

Info from Ajax: Page viewed long time

User IP address: 23.21.77.98

Browser identity: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6)

Putting Ajax on the Page

Below is the Ajax source code for the page. It may be put anywhere on the page that is convenient — in the head or body area.

A customization note follows the Ajax source code.

<script type="text/javascript">
// Will Bontrager Software LLC
// https://www.willmaster.com/
// July 25, 2020

// Customization ///////////////////
// Specify URL of PHP script for emailing event info.
// Recommend specifying URL relative to document root.

var URLofPHPscript = "/php/EventMail.php";

// End of customization ///////////////////
function EventHappened(message)
{
   var http = new XMLHttpRequest();
   if( ! http ) { return; }
   var params = new Array();
   params.push( "info=" + encodeURIComponent(message) );
   params.push( "url=" + encodeURIComponent(document.URL) );
   params.push( "ip=" + encodeURIComponent("<?php echo($_SERVER['REMOTE_ADDR']) ?>") );
   params.push( "ua=" + encodeURIComponent("<?php echo($_SERVER['HTTP_USER_AGENT']) ?>") );
   http.onreadystatechange = function() {};
   http.open("POST",URLofPHPscript,true);
   http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http.send(params.join("&"));
   return true;
}
</script>

Customization note —

In the script, you'll see the variable URLofPHPscript and it's /php/EventMail.php value. Replace /php/EventMail.php with the URL of the EventMail.php script you uploaded to your server in the previous step.

Use the URL of EventMail.php that is relative to document root.

To determine a URL relative to document root, take the absolute URL and remove the protocol and domain name. As an example, if https://example.com/php/EventMail.php was the absolute URL, then /php/EventMail.php would be the URL relative to document root.

With EventMail.php on the server and the Ajax on the page, you are ready to insert the code that will initiate an email to you.

Make Certain Events Notify the Ajax

Here, you'll find examples of kinds of events and how to make the event notify Ajax.

The basic Ajax call is:

EventHappened('INFORMATION');

The INFORMATION is replaced with the information or message to include in the email sent to you.

In the following examples, the Ajax call is published in red, except for the message that Ajax will send to the EventMail.php script, which is in blue. If you wish to change the information, change the blue text.

Page Load Event Notice

Let's do a page load notice for the first example event. Here is the code:

<script type="text/javascript">
EventHappened('Page has loaded');
</script>

Place the page load event JavaScript at the end of the web page source code, immediately above the cancel </body> tag.

The reason for that position is because the event fires off an email as soon as the browser reads the JavaScript. If someone interrupts the page load before the source code is loaded, no page load event happens.

Form Submission Event Notice

Let's now do an example of a form sending an email when the form is submitted.

<form 
   type="post" 
   action="script.php" 
   onsubmit="return EventHappened('Form was submitted')">
Email: <input type="email" name="email">
<input 
   type="submit">
</form>

The key here is the value of the onsubmit attribute.

Put that onsubmit attribute and its value into the form tag of forms that you need to stay on top of so an email is sent upon submission.

Most forms will let you do that. But some use the onsubmit attribute for something else.

If the onsubmit attribute is already being used, the value can also be specified in the submit button tag, but as an onclick attribute. Here is an example.

<form 
   type="post" 
   action="script.php">
Email: <input type="email" name="email">
<input 
   type="submit" 
   onclick="return EventHappened('Form was submitted')">
</form>

Element Click Event Notice

When an element is clicked or tapped, such as the area of a div or an image in an img tag, the event can cause an email to be sent. Here are examples of each.

<div 
   onclick="EventHappened('The div was clicked')">
DIV CONTENT
</div>
<img 
   src="https://www.willmaster.com/images/wmlogo_icon.gif"
   style="width:50px; height:50px; border:none; outline:none;"
   alt="Willmaster logo"
   onclick="EventHappened('The image was clicked')">

A note about A tag links — The above element click event won't work with links unless they are formatted in a special way. What happens is that the browser starts to load a different web page before the Ajax JavaScript at the original web page can complete.

See When JavaScript Needs to Run Before Loading Another Page for information about formatting a link so the Ajax JavaScript has time to run.

Page Scroll Event Notice

The JavaScript for the page scroll event notice can be put anywhere on the web page. Somewhere close to, but above, the cancel </body> tag would work.

Here is the JavaScript.

<script type="text/javascript">
var ScrollReported = false;
function SendScrolledEmail()
{
   if(!ScrollReported)
   {
      ScrollReported = true;
      EventHappened("Page was scrolled");
   }
}
window.onscroll = SendScrolledEmail;
</script>

The JavaScript should notify Ajax no more than once per page load. Otherwise, you could potentially get hundreds of emails about this event.

Continuous Viewing Event Notice

The continuous page view event is triggered when the page has been in the browser more than a certain length of time.

There is one special customization. It is noted below the source code.

<script type="text/javascript">
var ViewedSeconds = 90;
setTimeout( "EventHappened('Page viewed long time')", parseInt(ViewedSeconds*1000) );
</script>

Customization note —

In the JavaScript, you'll see the value 90 assigned to the ViewedSeconds variable. The 90 tells the browser how long to wait before notifying Ajax. Change 90 to the number of seconds you want the page to be viewed before Ajax sends you a notification.

Overview

JavaScript can't, by itself, send email. That's why Ajax is used to launch an email-sending PHP script.

To cause an email to be sent upon the occurrence of a certain event, the Ajax engine is told, in essence, "now is the time to send the email." This article has examples of how to do that for various events.

(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