2

Issue related to

Video lazy loading skipping first video in every list

The css shows up with a black box and the arrow, but script doesn't seem to run after ajax load from pagination, and also when clicking through from JComments Latest link, which adds #comment-43 to the end of the link to target a specific comment (just picked 43 at random).

Tried adding the script multiple places, putting onload type events in div tag, onhashchange, separating the function and calling it from different places, just doesn't want to load after those 2 cases. Click through direct url to page Page 1 will load preview images, then you click page 2 and no preview/video, back to 1 and no preview/video.

Not familiar with ajax, there are a couple of ajax files in the component directory, could I possibly add something to them?

2 files from components/com_jcomments/libraries/joomlatune

ajax.js & ajax.php, here is ajax.php:

<?php
/**
 * Simple AJAX library (based on code XAJAX library - http://www.xajaxproject.org)
 *
 * @version 1.0
 * @package JoomlaTune.Framework
 * @author Sergey M. Litvinov ([email protected])
 * @copyright (C) 2006-2013 by Sergey M. Litvinov (http://www.joomlatune.ru)
 * @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html
 */

defined('_JEXEC') or die;

// Check for double include
if (!defined ('JOOMLATUNE_AJAX'))
{
    define ('JOOMLATUNE_AJAX', 1);

    class JoomlaTuneAjaxResponse
    {
        var $aCommands;
        var $xml;
        var $sEncoding;

        function JoomlaTuneAjaxResponse($sEncoding='utf-8')
        {
            $this->aCommands = array();
            $this->sEncoding = $sEncoding;
        }

        function addCommand($aAttributes, $mData)
        {
            $aAttributes['d'] = $mData;
            $this->aCommands[] = $aAttributes;
        }

        function addAssign($sTarget,$sAttribute,$sData)
        {
            $scripts = array();
            // small hack to auto execute JavaScript code returned through ajax
            if (preg_match('/\<script/', $sData)) {
                $regexp = '/<script[^>]+>(.*?)<\/script>/ism';
                $matches = array();
                preg_match_all($regexp, $sData, $matches);

                for ($i = 0, $n = count($matches[0]); $i < $n; $i++) {
                    if ($matches[1][$i] != '') {
                        $sData = str_replace($matches[0][$i], '', $sData);
                        $scripts[] = trim(preg_replace(array('#^<!--#ism', '#\/\/-->$#ism'), '', $matches[1][$i]));
                    }
                }
            }

            $this->addCommand(array('n'=>'as','t'=>$sTarget,'p'=>$sAttribute),$sData);

            if (count($scripts)) {
                foreach ($scripts as $script) {
                    $this->addCommand(array('n'=>'js'),$script);
                }
            }

            return $this;
        }

        function addScript($sJS)
        {
            $sJS = str_replace("\n", '\n', $sJS);
            $sJS = str_replace("\r", '', $sJS);
            $this->addCommand(array('n'=>'js'),$sJS);
            return $this;
        }

        function addAlert($sMsg)
        {
            $this->addCommand(array('n'=>'al'),$sMsg);
            return $this;
        }

        function getOutput()
        {
            $output = '';
            if (is_array($this->aCommands)) {
                $output = JoomlaTuneAjaxResponse::php2js($this->aCommands);
            }
            if (trim($this->sEncoding)) {
                @header('content-type: text/plain; charset="'.$this->sEncoding.'"');
            }
            return $output;
        }

        /**
        * This function taken from JsHttpRequest library
        * JsHttpRequest: PHP backend for JavaScript DHTML loader.
        * (C) Dmitry Koterov, http://en.dklab.ru
        *
        * Convert a PHP scalar, array or hash to JS scalar/array/hash. This function is
        * an analog of json_encode(), but it can work with a non-UTF8 input and does not
        * analyze the passed data. Output format must be fully JSON compatible.
        *
        * @param mixed $a   Any structure to convert to JS.
        * @return string    JavaScript equivalent structure.
        */
        function php2js($a=false)
        {
            if (is_null($a)) return 'null';
            if ($a === false) return 'false';
            if ($a === true) return 'true';
            if (is_scalar($a)) {
                if (is_float($a)) {
                    $a = str_replace(",", ".", strval($a));
                }
                // All scalars are converted to strings to avoid indeterminism.
                // PHP's "1" and 1 are equal for all PHP operators, but
                // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend,
                // we should get the same result in the JS frontend (string).
                // Character replacements for JSON.
                static $jsonReplaces = array(
                array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
                array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')
                );
                return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
            }
            $isList = true;
            for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
                if (key($a) !== $i) {
                    $isList = false;
                    break;
                }
            }
            $result = array();
            if ($isList) {
                foreach ($a as $v) {
                    $result[] = JoomlaTuneAjaxResponse::php2js($v);
                }
                return '[ ' . join(', ', $result) . ' ]';
            } else {
                foreach ($a as $k => $v) {
                    $k = JoomlaTuneAjaxResponse::php2js($k);
                    $v = JoomlaTuneAjaxResponse::php2js($v);
                    $result[] = $k . ': ' . $v;
                }
                return '{ ' . join(', ', $result) . ' }';
            }
        }
    }

    class JoomlaTuneAjax
    {
        var $aFunctions;
        var $aObjects;
        var $aFunctionRequestTypes;
        var $sRequestURI;
        var $sEncoding;

        function JoomlaTuneAjax($sRequestURI="",$sEncoding='utf-8')
        {
            $this->aFunctions = array();
            $this->aFunctionRequestTypes = array();
            $this->aObjects = array();
            $this->aFunctionIncludeFiles = array();
            $this->sRequestURI = $sRequestURI;
            if ($this->sRequestURI == "") {
                $this->sRequestURI = $this->_detectURI();
            }
            $this->setCharEncoding($sEncoding);
        }

        function setCharEncoding($sEncoding)
        {
            $this->sEncoding = $sEncoding;
        }

        function registerFunction($mFunction,$sRequestType=1)
        {
            if (is_array($mFunction)) {
                $this->aFunctions[$mFunction[0]] = 1;
                $this->aFunctionRequestTypes[$mFunction[0]] = $sRequestType;
                $this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
            } else {
                $this->aFunctions[$mFunction] = 1;
                $this->aFunctionRequestTypes[$mFunction] = $sRequestType;
            }
        }

        function processRequest()
        {
            return $this->processRequests();
        }

        function _isObjectCallback($sFunction)
        {
            if (array_key_exists($sFunction, $this->aObjects)) {
                return true;
            }
            return false;
        }
        function _callFunction($sFunction, $aArgs)
        {
            if ($this->_isObjectCallback($sFunction)) {
                $mReturn = call_user_func_array($this->aObjects[$sFunction], $aArgs);
            } else if (array_key_exists($sFunction, $this->aFunctions)) {
                $mReturn = call_user_func_array($sFunction, $aArgs);
            }
            return $mReturn;
        }

        function processRequests()
        {
            $sFunctionName = $_REQUEST["jtxf"];
            $aArgs = isset($_REQUEST["jtxa"]) ? $_REQUEST["jtxa"] : array();

            if (!array_key_exists($sFunctionName, $this->aFunctions)) {
                $oResponse = new JoomlaTuneAjaxResponse();
                $oResponse->addAlert("Unknown Function $sFunctionName.");
            } else {
                $oResponse = $this->_callFunction($sFunctionName, $aArgs);
            }
            @header('content-type: text/plain; charset="'.$this->sEncoding.'"');
            print $oResponse->getOutput();
            exit();
        }

        function _detectURI() {
            $aURL = array();

            // Try to get the request URL
            if (!empty($_SERVER['REQUEST_URI'])) {
                $_SERVER['REQUEST_URI'] = str_replace(array('"',"'",'<','>'), array('%22','%27','%3C','%3E'), $_SERVER['REQUEST_URI']);
                $aURL = parse_url($_SERVER['REQUEST_URI']);
            }

            // Fill in the empty values
            if (empty($aURL['scheme'])) {
                if (!empty($_SERVER['HTTP_SCHEME'])) {
                    $aURL['scheme'] = $_SERVER['HTTP_SCHEME'];
                } else {
                    $aURL['scheme'] = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http';
                }
            }

            if (empty($aURL['host'])) {
                if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
                    if (strpos($_SERVER['HTTP_X_FORWARDED_HOST'], ':') > 0) {
                        list($aURL['host'], $aURL['port']) = explode(':', $_SERVER['HTTP_X_FORWARDED_HOST']);
                    } else {
                        $aURL['host'] = $_SERVER['HTTP_X_FORWARDED_HOST'];
                    }
                } else if (!empty($_SERVER['HTTP_HOST'])) {
                    if (strpos($_SERVER['HTTP_HOST'], ':') > 0) {
                        list($aURL['host'], $aURL['port']) = explode(':', $_SERVER['HTTP_HOST']);
                    } else {
                        $aURL['host'] = $_SERVER['HTTP_HOST'];
                    }
                } else if (!empty($_SERVER['SERVER_NAME'])) {
                    $aURL['host'] = $_SERVER['SERVER_NAME'];
                } else {
                    print "Error: ajax failed to automatically identify your Request URI.";
                    print "Please set the Request URI explicitly when you instantiate the jtajax object.";
                    exit();
                }
            }

            if (empty($aURL['port']) && !empty($_SERVER['SERVER_PORT'])) {
                $aURL['port'] = $_SERVER['SERVER_PORT'];
            }

            if (empty($aURL['path'])) {
                if (!empty($_SERVER['PATH_INFO'])) {
                    $sPath = parse_url($_SERVER['PATH_INFO']);
                } else {
                    $sPath = parse_url($_SERVER['PHP_SELF']);
                }
                $aURL['path'] = str_replace(array('"',"'",'<','>'), array('%22','%27','%3C','%3E'), $sPath['path']);
                unset($sPath);
            }

            if (!empty($aURL['query'])) {
                $aURL['query'] = '?'.$aURL['query'];
            }

            // Build the URL: Start with scheme, user and pass
            $sURL = $aURL['scheme'].'://';
            if (!empty($aURL['user'])) {
                $sURL.= $aURL['user'];
                if (!empty($aURL['pass'])) {
                    $sURL.= ':'.$aURL['pass'];
                }
                $sURL.= '@';
            }

            // Add the host
            $sURL.= $aURL['host'];

            // Add the port if needed
            if (!empty($aURL['port']) && (($aURL['scheme'] == 'http' && $aURL['port'] != 80) || ($aURL['scheme'] == 'https' && $aURL['port'] != 443))) {
                $sURL.= ':'.$aURL['port'];
            }

            // Add the path and the query string
            $sURL.= $aURL['path'].@$aURL['query'];

            // Clean up
            unset($aURL);
            return $sURL;
        }
    }
} // end of double include check

I can post ajax.js, just not sure how much space there is here and how much I can post. Try here starting on line 4: https://ideone.com/8df01C

Other file is components/jcomments/jcomments.ajax.php Try it here starting on line4: https://ideone.com/16szL9

The pagination code is added to component/com_jcomments/jcomments.php

public static function getCommentsTree($object_id, $object_group = 'com_content', $page = 0)
    {
        $object_id = (int)$object_id;
        $object_group = trim($object_group);

        $user = JFactory::getUser();
        $acl = JCommentsFactory::getACL();
        $config = JCommentsFactory::getConfig();

                $comments_per_page = $config->getInt('comments_per_page');
                $limitstart = 0;

        $total = JComments::getCommentsCount($object_id, $object_group, 'c.level = 0');

        if ($acl->canComment() == 0 && $total == 0) {
            return '';
        }

        if ($total > 0) {
            $options = array();
                        $options['pagination'] = 'tree';
            $options['object_id'] = $object_id;
            $options['object_group'] = $object_group;
            $options['published'] = $acl->canPublish() || $acl->canPublishForObject($object_id, $object_group) ? null : 1;
            $options['votes'] = $config->getInt('enable_voting');

            if ($comments_per_page > 0) {
                $page = (int)$page;

                require_once(JCOMMENTS_HELPERS . '/pagination.php');
                $pagination = new JCommentsPagination($object_id, $object_group);
                $pagination->setCurrentPage($page);
                                $pagination->setCommentsCount($total);

                $total_pages = $pagination->getTotalPages();
                $this_page = $pagination->getCurrentPage();
                $limitstart = $pagination->getLimitStart();
                $comments_per_page = $pagination->getCommentsPerPage();

                $options['limit'] = $comments_per_page;
                $options['limitStart'] = $limitstart;
            }

            $rows = JCommentsModel::getCommentsList($options);

        } else {
            $rows = array();
        }

        $tmpl = JCommentsFactory::getTemplate($object_id, $object_group);
        $tmpl->load('tpl_tree');
        $tmpl->load('tpl_comment');

        if (count($rows)) {

            $isLocked = ($config->getInt('comments_locked', 0) == 1);

            $tmpl->addVar('tpl_tree', 'comments-refresh', intval(!$isLocked));
            $tmpl->addVar('tpl_tree', 'comments-rss', intval($config->getInt('enable_rss') && !$isLocked));
            $tmpl->addVar('tpl_tree', 'comments-can-subscribe', intval($user->id && $acl->check('enable_subscribe') && !$isLocked));
            $tmpl->addVar('tpl_tree', 'comments-count', count($rows));
                        $tmpl->addVar('tpl_tree', 'comments-nav-bottom', 1);

            if ($user->id && $acl->check('enable_subscribe')) {
                require_once(JCOMMENTS_SITE . '/jcomments.subscription.php');
                $manager = JCommentsSubscriptionManager::getInstance();
                $isSubscribed = $manager->isSubscribed($object_id, $object_group, $user->id);
                $tmpl->addVar('tpl_tree', 'comments-user-subscribed', $isSubscribed);
            }

            $i = 1;

            JCommentsEventHelper::trigger('onJCommentsCommentsPrepare', array(&$rows));

            if ($acl->check('enable_gravatar')) {
                JCommentsEventHelper::trigger('onPrepareAvatars', array(&$rows));
            }

            require_once(JCOMMENTS_LIBRARIES . '/joomlatune/tree.php');

            $tree = new JoomlaTuneTree($rows);
            $items = $tree->get();

            foreach ($rows as $row) {
                // run autocensor, replace quotes, smilies and other pre-view processing
                JComments::prepareComment($row);

                // setup toolbar
                if (!$acl->canModerate($row)) {
                    $tmpl->addVar('tpl_comment', 'comments-panel-visible', 0);
                } else {
                    $tmpl->addVar('tpl_comment', 'comments-panel-visible', 1);
                    $tmpl->addVar('tpl_comment', 'button-edit', $acl->canEdit($row));
                    $tmpl->addVar('tpl_comment', 'button-delete', $acl->canDelete($row));
                    $tmpl->addVar('tpl_comment', 'button-publish', $acl->canPublish($row));
                    $tmpl->addVar('tpl_comment', 'button-ip', $acl->canViewIP($row));
                    $tmpl->addVar('tpl_comment', 'button-ban', $acl->canBan($row));
                }

                $tmpl->addVar('tpl_comment', 'comment-show-vote', $config->getInt('enable_voting'));
                $tmpl->addVar('tpl_comment', 'comment-show-email', $acl->canViewEmail($row));
                $tmpl->addVar('tpl_comment', 'comment-show-homepage', $acl->canViewHomepage($row));
                $tmpl->addVar('tpl_comment', 'comment-show-title', $config->getInt('comment_title'));
                $tmpl->addVar('tpl_comment', 'button-vote', $acl->canVote($row));
                $tmpl->addVar('tpl_comment', 'button-quote', $acl->canQuote($row));
                $tmpl->addVar('tpl_comment', 'button-reply', $acl->canReply($row));
                $tmpl->addVar('tpl_comment', 'button-report', $acl->canReport($row));
                $tmpl->addVar('tpl_comment', 'avatar', $acl->check('enable_gravatar') && !$row->deleted);

                if (isset($items[$row->id])) {
                    $tmpl->addVar('tpl_comment', 'comment-number', '');
                    $tmpl->addObject('tpl_comment', 'comment', $row);
                    $items[$row->id]->html = $tmpl->renderTemplate('tpl_comment');
                    $i++;
                }
            }

            $tmpl->addObject('tpl_tree', 'comments-items', $items);

            // build page navigation
            if (($comments_per_page > 0) && ($total_pages > 1)) {
                $tmpl->addVar('tpl_tree', 'comments-nav-first', 1);
                $tmpl->addVar('tpl_tree', 'comments-nav-total', $total_pages);
                $tmpl->addVar('tpl_tree', 'comments-nav-active', $this_page);

                $pagination = $config->get('comments_pagination');

                // show top pagination
                if (($pagination == 'both') || ($pagination == 'top')) {
                    $tmpl->addVar('tpl_tree', 'comments-nav-top', 1);
                }

                // show bottom pagination
                if (($pagination == 'both') || ($pagination == 'bottom')) {
                    $tmpl->addVar('tpl_tree', 'comments-nav-bottom', 1);
                }
            }
            unset($rows);
        }

        return $tmpl->renderTemplate('tpl_tree');
    }

and component/com_jcomments/tpl/default/tpl_tree.php

  function getNavigation() {
    if ($this->getVar('comments-nav-top') == 1 
    ||  $this->getVar('comments-nav-bottom') == 1) {
      $active_page = $this->getVar('comments-nav-active', 1);
      $first_page = $this->getVar('comments-nav-first', 0);
      $total_page = $this->getVar('comments-nav-total', 0);

      if ($first_page != 0 && $total_page != 0) {
      $object_id = $this->getVar('comment-object_id');
      $object_group = $this->getVar('comment-object_group');

      $content = '';

        // number of visible pages
        $pp = 14;

        $fp = $active_page - $pp/2;
        if ($fp <= 0) {
        $fp = 1;
        }

        $lp = $fp + $pp;
        if ($lp > $total_page) {
        $lp = $total_page;
        }

        if ($lp - $fp < $pp && $pp < $total_page) {
        $fp = $lp - $pp;
        }

        if ($fp > 1) {
        $content .= '<span onclick="jcomments.showPage('.$object_id.', \''.$object_group.'\', '.($active_page-1).');" class="page" onmouseover="this.className=\'hoverpage\';" onmouseout="this.className=\'page\';" >&laquo;</span>';
        }

        for ($i=$fp; $i <= $lp; $i++) {
          if ($i == $active_page) {
          $content .= '<span class="activepage"><b>'.$i.'</b></span>';
          } else {
          $content .= '<span onclick="jcomments.showPage('.$object_id.', \''.$object_group.'\', '.$i.');" class="page" onmouseover="this.className=\'hoverpage\';" onmouseout="this.className=\'page\';" >'.$i.'</span>';
          }
        }

        if ($lp < $total_page) {
          $content .= '<span onclick="jcomments.showPage('.$object_id.', \''.$object_group.'\', '.($lp+1).');" class="page" onmouseover="this.className=\'hoverpage\';" onmouseout="this.className=\'page\';" >&raquo;</span>';
        }

      return $content;
      }
    }
        return '';
  }  
11
  • Probably a good idea to paste some of the ajax codes here in the question. Commented Jan 19, 2019 at 3:56
  • 1
    Before dealing with the ajax, you should check two things which are errors according to the console: 1. jQuery is not defined in .../com_jcomments/js/jcomments-v2.3.js:378:9 - probably you inserted a short jQuery script at the end of this .js file, I suspect that it will not work here this way. Load that short script from somewhere else. 2. A closing curly bracket is missing from your youtube loading jQuery function somewhere (after function body).
    – Zollie
    Commented Jan 19, 2019 at 5:39
  • Took care of js file, don't see where curly bracket is missing though. Code is in linked related thread, all look to be there.
    – Mythic
    Commented Jan 19, 2019 at 6:02
  • Figure it has to be the ajax, I could be wrong though. The pagination works ok so far for the ones displayed in the separate profile page, loads all videos on every page. Hash isn't that big of a deal from Latest, if you're already on the page and had it loaded it just goes to the comment with video already loaded and working, just not from any other pages, goes to comment but no preview/video in any comments.
    – Mythic
    Commented Jan 19, 2019 at 6:17
  • As i see the console does not show any more js error if I load your page. That's good. The original problem is still present?
    – Zollie
    Commented Jan 19, 2019 at 8:36

1 Answer 1

2

First: I like your question and a lot of details that you provided. I like people on StackExchange who can ask questions properly, clearly with precise details. This separates the real developers from quite ignorant people. So I like your question, but: honestly it took me quite a while to understand your question. The long, actually from the point of view of your question, irrelevant details of your project can cause a bit confusion about what your question is. It's also true that many times happen with me the same, that I do not know how to ask a question about my issue. So the right question usually embrace the answer itself somewhere. :)

Your question simply: how to fire an javascript or jquery script after an ajax call. Or more precisely, after an ajax call is completed. Any ajax call. :) This is that simple now.

Of course this was a question of millions of developers before you so jQuery has a solution for this.

You have to use the jQuery .ajaxComplete() function. This function ignites when any ajax request is finished on a page. Since an ajax call is also a Global ajax event when completed. These events are triggered on the document, calling any handlers which may be listening.

Thus, my suggestion is, since you already have a well working javascript script to load the youtube videos' sources. Then you should just wrap that or call that with the jQuery .ajaxComplete() function, something like this:

$ = jQuery.noConflict();
$( document ).ajaxComplete(function() {
    videoListLoad();
});

function videoListLoad () {

    var youtube = document.querySelectorAll( ".youtube" );

    for (var i = 0; i < youtube.length; i++) {

        var source = "https://img.youtube.com/vi/"+ youtube[i].dataset.embed +"/hqdefault.jpg";

        var image = new Image();
        image.src = source;
        image.addEventListener( "load", function() {
            youtube[ i ].appendChild( image );
        }( i ) );

        youtube[i].addEventListener( "click", function() {

            var iframe = document.createElement( "iframe" );
            iframe.setAttribute( "frameborder", "0" );
            iframe.setAttribute( "allowfullscreen", "" );
            iframe.setAttribute( "src", "https://www.youtube.com/embed/"+ this.dataset.embed +"?rel=0&showinfo=0&autoplay=1" );

            this.innerHTML = "";
            this.appendChild( iframe );
        } );
    }
}

Create and load this additional script on your page (in the head for example) and try this and give me some feedback (Of course I have not tried this on your page). Do not touch your original script on your site, you just have to leave that there too. So you will have two similar scripts, one for normal page load and one for ajax events like pagination. Just to make sure it is clear for you.

More info on this jQuery function is here: http://api.jquery.com/ajaxcomplete/

You initial javascript function could be bound other way like:

$(document).bind("ajaxComplete", function(){ ...// your function... });

But I just wanted to give you an example which you can use on your page. I hope this will solve your issue.

(Of course, this can starts other new questions later, for example: how to unbind this function from other irrelevant ajax requests on the page but that's the question of another day)

UPDATE

Now, there is a possibility that the above will not work (if the ajax call is not jQuery ajax), however sounds very good, then the next valuable approach would be to build the video source loading .js function (script) in the ajax.js function which has to fire this function this way. So I copy here the edited ajax.js file and please use this instead of your file (keep the original ajax.js file though!! You can just rename it old-ajax.js or something.)

I just built in the videoloading function after the ajax response is processed. So you will see if it's successful this way.

/* based on xajax Javascript library (http://www.xajaxproject.org) */
if (!window.jtajax) {

    function jtAJAX()
    {
        this.options = {url: '',type: 'post',nocache: true,data: ''};

        this.$ = function(id) {if(!id){return null;}var o=document.getElementById(id);if(!o&&document.all){o=document.all[id];}return o;};
        this.extend = function(o, e){for(var k in (e||{}))o[k]=e[k];return o;};
        this.encode = function(t){return encodeURIComponent(t);};
        this.setup = function(options) {this.options = this.extend(this.options, options);};

        this.xhr = function()
        {
            var xhr = null;
            if ('undefined' != typeof XMLHttpRequest) xhr = new XMLHttpRequest();
            if (!xhr && 'undefined' != typeof ActiveXObject) {
                var msxmlhttp = new Array('Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0','Msxml2.XMLHTTP','Microsoft.XMLHTTP');
                for (var i=0;i<msxmlhttp.length;i++){try{xhr=new ActiveXObject(msxmlhttp[i]);}catch(e){xhr=null;}}
            }
            return xhr;
        };

        this.form2query = function(sId)
        {
            var frm = this.$(sId);
            if (frm && frm.tagName.toUpperCase() == 'FORM') {
                var e = frm.elements, query = [];
                for (var i=0; i < e.length; i++) {
                    var name = e[i].name;
                    if (!name) continue;
                    if (e[i].type && ('radio' == e[i].type || 'checkbox' == e[i].type) && false === e[i].checked) continue;
                    if ('select-multiple' == e[i].type) {
                        for (var j = 0; j < e[i].length; j++) {
                            if (true === e[i].options[j].selected)
                                query.push(name+"="+this.encode(e[i].options[j].value));
                        }
                    } else { query.push(name+"="+this.encode(e[i].value));
                    }
                }
                return query.join('&');
            }
            return '';
        };

        this.startLoading = function(){};
        this.finishLoading = function(){};

        this.ajax = function(options)
        {
            var xhr = this.xhr();
            if (!xhr) return false;
            var o = this.extend(this.options, options);
            var url = o.url, jtx = this;url=url.replace(/&amp;/g,'&');
            var r=url;var h=location.hostname,d,i1,i2;i1=r.indexOf('://');if(i1!=-1){i2=r.indexOf('/',i1+3);if(i2!=-1){d=r.substring(i1+3,i2);if(d!=h){if(location.port!=''){h=h+':'+location.port;}r=r.replace(d,h);url=r;}}}

            if ('get' == o.type) {
                if (true === o.nocache) {
                    var ts=new Date().getTime();
                    url += (url.indexOf("?")==-1 ? '?' : '&') + '_jtxr_' + ts;
                }
                if (o.data) {
                    url += (url.indexOf("?")==-1 ? '?' : '&') + o.data;
                    o.data = null;
                }
            }

            xhr.open(o.type.toUpperCase(), url, true);

            if ('post' == o.type)
                try {xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");}catch(e){}
            if (true === o.nocache)
                xhr.setRequestHeader('If-Modified-Since', 'Thu, 01 Jan 1970 00:00:00 GMT');

            xhr.onreadystatechange = function() {
                if (xhr.readyState != 4) return;
                jtx.finishLoading();
                if (xhr.status==200) {
                    jtx.processResponse(xhr.responseText);
                }
                delete xhr;
                xhr = null;
            };
            try {
                jtx.startLoading();
                xhr.send(o.data);
            } catch(e) { jtx.finishLoading(); }

            delete jtx;
            delete xhr;
            delete o;
            return true;
        };

        this.call = function(sFunction, aArgs, sType, sForm)
        {
            var params = 'jtxf=' + this.encode(sFunction);
            if (aArgs) {
                for (var i=0;i<aArgs.length;i++) {
                    params += '&jtxa[]=' + this.encode(aArgs[i]);
                }
            } else if (sForm) {
                params += '&' + this.form2query(sForm);
            }

            this.ajax({type: sType, data: params});
            return true;
        };

        this.processResponse = function(sText)
        {
            if(sText==='') return false;
            if(sText.substring(0,3)!='[ {'){var idx=sText.indexOf('[ {');sText=sText.substr(idx);}
            var result;try {result=eval(sText);}catch(e){}
            if ('undefined' == typeof result) {return false;}

            var cmd, id, property, data, obj = null;

            for (var i=0;i<result.length;i++) {
                cmd         = result[i]['n'];
                id      = result[i]['t'];
                property    = result[i]['p'];
                data        = result[i]['d'];
                obj         = this.$(id);

                switch(cmd) {
                    case 'as': if(obj){eval("obj."+property+"=data;");} break;
                    case 'al': if(data){alert(data);} break;
                    case 'js': if(data){eval(data);} break;
                    default: this.error('Unknown command: ' + cmd);break;
                }
            }

            delete result;
            delete cmd;
            delete id;
            delete property;
            delete data;
            delete obj;
            this.videoListLoad();
            return true;
        };

        this.error = function(){};

        this.videoListLoad = function()
        {

            var youtube = document.querySelectorAll( ".youtube" );

            for (var i = 0; i < youtube.length; i++) {

                var source = "https://img.youtube.com/vi/"+ youtube[i].dataset.embed +"/hqdefault.jpg";

                var image = new Image();
                image.src = source;
                image.addEventListener( "load", function() {
                    youtube[ i ].appendChild( image );
                }( i ) );

                youtube[i].addEventListener( "click", function() {

                    var iframe = document.createElement( "iframe" );
                    iframe.setAttribute( "frameborder", "0" );
                    iframe.setAttribute( "allowfullscreen", "" );
                    iframe.setAttribute( "src", "https://www.youtube.com/embed/"+ this.dataset.embed +"?rel=0&showinfo=0&autoplay=1" );

                    this.innerHTML = "";
                    this.appendChild( iframe );
                } );
            }

        };

    }

    var jtajax = new jtAJAX();
}
13
  • Thanks Zollie. Going to have to play around with it for a bit, doesn't seem to be working anyplace I put it.
    – Mythic
    Commented Jan 23, 2019 at 18:59
  • @Mythic - then I'll update my answer on this a bit later. I see the script on your page now.
    – Zollie
    Commented Jan 23, 2019 at 19:08
  • 1
    @Mythic - I updated my answer, please try that new edited ajax.js file instead of the original file. Keep me posted about the results.
    – Zollie
    Commented Jan 23, 2019 at 19:45
  • Works good now Zollie. Thank you very much, I never would have been able to incorporate that script there. It also even works with the hashtag links from Latest Comments. Very nice. First glances anyway, will post back if any other hiccups pop up.
    – Mythic
    Commented Jan 23, 2019 at 20:34
  • 1
    @Mythic - I'm not sure if they have javascript on their phone browser on in their browser settings.. That can cause this problem for them.
    – Zollie
    Commented Jan 27, 2019 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.