Search code examples
phpjoomla

In Joomla, why does typeahead break when used in a module?


Using Joomla version 3.7.5 with Wright template.

I have a module in the left sidebar which has 2 typeahead fields getting data from a local database. The php code is referenced using include_once via the sourcerer plugin.

The typeahead does not work when used in the module. But - if I use the exact same code in an article, the typeahead works correctly.

Do articles and modules load/behave differently? I would appreciate it if someone could explain this behaviour.

The relevant parts of the code follow.

PHP - the first lines of code are:

JHtml::_('script', './templates/js_wright/wright/js/jquery.js');
JHtml::_('script', './styling/bootstrap3-typeahead.min.js');
$document->addStyleSheet("./media/jui/css/bootstrap.css",'text/css',"screen");

HTML - in the form:

<div class="input-prepend span8"><span class="add-on" ><i class="icon-map-marker" ></i></span><input autocomplete="off" style="border-color:#F7980F;" class="typeahead" id="inputIcon" type="text" name="collectionpoint"  /></div>

Javascript:

$('input.typeahead').typeahead({
        source:  function (query, process) {
        return $.get('./towns.php', { query: query }, function (data) {
                console.log(data);
                data = $.parseJSON(data);
                return process(data);
            });
        }
    });

and in the towns.php:

$sql = "SELECT Town FROM lkp_towns 
        WHERE Town LIKE '%".$_GET['query']."%'
        LIMIT 5"; 
        $result = $mysqli->query($sql);

        $json = [];

        while($row = $result->fetch_assoc()){
             $json[] = $row['Town'];
        }
        echo json_encode($json);

Solution

  • Worked it out.

    Joomla does not see a module as a seperate page but rather as a nested div of the main page.

    Moving the following lines to the main article page on which the module displays solved the problem as the .js needs to be referenced before anything else has loaded:

    Removed this from the module and included it in the article:

    JHtml::_('script', './templates/js_wright/wright/js/jquery.js');
    JHtml::_('script', './styling/bootstrap3-typeahead.min.js');
    $document->addStyleSheet("./media/jui/css/bootstrap.css",'text/css',"screen");