This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

yozDev
yozDev

Im trying to create a very simple plugin that tracks site visits. I need to get the page referrer using JS document.referrer, pass it to a variable, and send that variable to the plugin controller or to the component, so I can store it in the database. I've been struggling with this for days...Tried everything I found on Google...Nothing works. Please, help :(

The script using vanilla JS and PHP is really easy to implement. The problem is to integrate it in OctoberCMS :(

// js
(function(){

    function makeXHRRequest( url, callback, method, dataType ) {
      if(!window.XMLHttpRequest ) {
        return null;
      }
      var req = new XMLHttpRequest();
      method = method || 'GET';
      dataType = dataType || 'text/plain';
      req.open( method, url );
      req.setRequestHeader('Content-Type', dataType);

      req.onreadystatechange = function() {
        if( req.readyState === 4 ) { 
          if( req.status === 200 ) {
            callback.success(req);
          }
          else {
             callback.failure(req);
          }
        }
      }
      req.send(); 
      return req; 
    }

    // current page url
    function getCurrentPage(){
        var urlPath = window.location.pathname;
        var domain  = window.location.hostname;
        var hostName;
        if (urlPath === '/'){
            hostName = urlPath.replace(urlPath, domain);
            return hostName;
        }
        else {
           return urlPath;
        }
    }

    // page referrer
    function getPageReferrer(){
      return document.referrer;
    }

    function RequestPageInfo() {
      var pageReferrer = getPageReferrer();
      var currentPage  = getCurrentPage();

      var queryVars = 'current_page='+currentPage+'&page_referrer='+pageReferrer;

      var callback = {
          success: function(req) {
           document.getElementById('page-result').innerHTML = req.responseText;
          },
          failure: function(req) {
           document.getElementById('page-result').innerHTML = 'An error has occurred.';
          }
      }

      // request data
      makeXHRRequest('tvisitor.php?'+queryVars, callback, 'POST', 'application/json' );
    }

    window.onload = function() {
      RequestPageInfo();
    };

})();
// visitor.php
// get ajax requested page url vars
$referrerPage = isset($_GET['page_referrer']) ? $_GET['page_referrer'] : "";
$PageUrl  = isset($_GET['current_page']) ?  $_GET['current_page'] : "";

Last updated

1-1 of 1

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.