Custom Module not working unless logged in Topic is solved

For Joomla! 5.x Coding related discussions, you could also use: http://groups.google.com/group/joomla-dev-general

Moderators: ooffick, General Support Moderators

Forum rules
Forum Rules
Absolute Beginner's Guide to Joomla! <-- please read before posting, this means YOU.
Forum Post Assistant - If you are serious about wanting help, you will use this tool to help you post.
Windows Defender SmartScreen Issues <-- please read this if using Windows 10.
Post Reply
Martyn1
Joomla! Apprentice
Joomla! Apprentice
Posts: 10
Joined: Thu Feb 03, 2022 10:19 pm

Custom Module not working unless logged in

Post by Martyn1 » Sat Feb 03, 2024 11:07 pm

Hello all,

Some members kindly pointed me in the direction of some information for learning a while ago so I could produce my first extension for Joomla. I detailed what I am trying to achieve in that post. see here for more info viewtopic.php?f=831&t=994295 this explains what the module I have created does.

After alot of reading, trial and error I now have a working module for the most part. I have run into an issue which I cant seem to figure out. I am assuming I have got something wrong in my code. When logged into the site the form in my module works as expected and returns the response. However I need the module to work even when not logged in. Below is the code from my files, can anyone guide me with what is wrong and stopping it from working unless logged in. if you type a number into the search and submit, it shows in the url when logged in but does not if not logged in and instead of a response it shows the below message.
Screenshot 2024-02-03 224359.jpg
Below shows what you get when logged in. this is what I need when not logged in. The 123456 in the picture below shows in the URL. It does not in the picture above when not logged in
Screenshot 2024-02-03 225711.jpg
MymodHelper.php

Code: Select all

<?php

namespace Mps\Module\Mymod\Site\Helper;

// No direct access to this file
defined('_JEXEC') or die;

use Joomla\CMS\Factory;

class MymodHelper
{
	public static function getPeriod($params)
	{

	if(isset($_GET['search']))
		{
			$filtervalues = $_GET['search'];
			$db = Factory::getDbo();
			$query = $db
				->getQuery(true)
				->select('period')
				->from($db->quoteName('#__mymod'))
				->where($db->quoteName('first') . "<=" . $db->quote($filtervalues))
				->andwhere($db->quoteName('last') . ">=" . $db->quote($filtervalues));

				$db->setQuery($query);
			$result = $db->loadResult();

		return $result;
		}
	}
}
Default.php

Code: Select all

<?php

defined('_JEXEC') or die;

use Joomla\CMS\HTML\HTMLHelper;
use Mps\Module\Mymod\Site\Helper\MymodHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;

?>
<form action="<?php echo Route::_( 'index.php?' . Session::getFormToken() .'=1' ); ?>" method="get">
	<div class="uk-grid">	
		<div>
			<div class="uk-inline">
				<span class="uk-form-icon" uk-icon="icon: search"></span>
				<input class="uk-input uk-form-large form-control" type="text" name="search" required value="<?php if(isset($_GET['search'])){echo $_GET['search'];} ?>" placeholder="Engine Number">
			</div>
		</div>
		<div>
			<button class="uk-button uk-button-primary uk-button-large" type="submit">Submit</button>
		</div>
	</div>	
  <?php
if (!$result)
{
    return;
}
?>
<div class="uk-table">
	<tr>
		<h2 class="uk-text-uppercase"><?php echo $result; ?></h2>
	</tr>
</div>
</form>
mod_mymod.php

Code: Select all

<?php

defined('_JEXEC') or die;

use Joomla\CMS\Helper\ModuleHelper;
use Mps\Module\Mymod\Site\Helper\MymodHelper;

$result = MymodHelper::getPeriod($params, $app);

require ModuleHelper::getLayoutPath('mod_mymod', $params->get('layout', 'default'));
Thankyou in advance for anyone who helps.

Martyn
Forum Post Assistant (v1.6.6) : 3-Feb-2024 wrote:
Basic Environment :: wrote:Joomla! Instance :: Joomla! 5.0.2-Stable (Kuboresha) 9-January-2024
Joomla! Configured :: Yes | Read-Only (444) |
Configuration Options :: Offline: false | SEF: true | SEF Suffix: false | SEF ReWrite: false | .htaccess/web.config: No | GZip: false | Cache: false | CacheTime: 15 | CacheHandler: file | CachePlatformPrefix: false | FTP Layer: N/A | Proxy: false | LiveSite: | Session lifetime: 15 | Session handler: database | Shared sessions: false | SSL: 0 | Error Reporting: maximum | Site Debug: true | Language Debug: false | Default Access: Public | Unicode Slugs: false | dbConnection Type: mysqli | PHP Supports J! 5.0.2: Yes | Database Supports J! 5.0.2: Yes | Database Credentials Present: Yes |

Host Configuration :: OS: Linux | OS Version: 4.4.400-icpu-097 | Technology: x86_64 | Web Server: Apache | Encoding: gzip, deflate | System TMP Writable: Yes | Free Disk Space : 725.13 GiB |

PHP Configuration :: Version: 8.2.14 | PHP API: cgi-fcgi | Session Path Writable: Yes | Display Errors: 0 | Error Reporting: 22517 | Log Errors To: | Last Known Error: | Register Globals: | Magic Quotes: | Safe Mode: | Allow url fopen: 1 | Open Base: | Uploads: 1 | Max. Upload Size: 64M | Max. POST Size: 64M | Max. Input Time: -1 | Max. Execution Time: 50000 | Memory Limit: -1

Database Configuration :: Version: 8.0.32 (Client:mysqlnd 8.2.14) | Database Size: 4.66 MiB | #of Tables with config prefix:  75 | #of other Tables:  0 | User Privileges : GRANT ALL
Detailed Environment :: wrote:PHP Extensions :: Core (8.2.14) | date (8.2.14) | libxml (8.2.14) | openssl (8.2.14) | pcre (8.2.14) | sqlite3 (8.2.14) | zlib (8.2.14) | bcmath (8.2.14) | bz2 (8.2.14) | calendar (8.2.14) | ctype (8.2.14) | curl (8.2.14) | dba (8.2.14) | dom (20031129) | hash (8.2.14) | fileinfo (8.2.14) | filter (8.2.14) | ftp (8.2.14) | gd (8.2.14) | gettext (8.2.14) | gmp (8.2.14) | json (8.2.14) | iconv (8.2.14) | SPL (8.2.14) | intl (8.2.14) | session (8.2.14) | ldap (8.2.14) | mbstring (8.2.14) | standard (8.2.14) | mysqlnd (mysqlnd 8.2.14) | exif (8.2.14) | mysqli (8.2.14) | PDO (8.2.14) | pdo_mysql (8.2.14) | pdo_sqlite (8.2.14) | Phar (8.2.14) | posix (8.2.14) | random (8.2.14) | Reflection (8.2.14) | imap (8.2.14) | shmop (8.2.14) | SimpleXML (8.2.14) | soap (8.2.14) | sodium (8.2.14) | tidy (8.2.14) | tokenizer (8.2.14) | xml (8.2.14) | xmlreader (8.2.14) | xmlwriter (8.2.14) | xsl (8.2.14) | zip (1.21.1) | cgi-fcgi (8.2.14) | Zend Engine (4.2.14) |
Potential Missing Extensions ::

Switch User Environment :: PHP CGI: Yes | Server SU: Yes | PHP SU: Yes | Potential Ownership Issues: No
Folder Permissions :: wrote:Core Folders :: images/ (705) | components/ (705) | modules/ (705) | plugins/ (705) | language/ (705) | templates/ (705) | cache/ (705) | logs/ (---) | tmp/ (705) | administrator/components/ (705) | administrator/modules/ (705) | administrator/language/ (705) | administrator/templates/ (705) | administrator/logs/ (705) | api/ (705) |

Elevated Permissions (First 10) ::
Database Information :: wrote:Database statistics :: Uptime: 139629 | Threads: 9 | Questions: 160875789 | Slow queries: 6 | Opens: 8608847 | Flush tables: 3 | Open tables: 6000 | Queries per second avg: 1152.166 |
Extensions Discovered :: wrote:Components :: Site ::
Core ::
3rd Party::

Components :: Admin ::
Core :: com_actionlogs (3.9.0) 1 | com_admin (4.0.0) 1 | com_ajax (4.0.0) 1 | com_associations (4.0.0) 1 | com_banners (4.0.0) 1 | com_cache (4.0.0) 1 | com_categories (4.0.0) 1 | com_checkin (4.0.0) 1 | com_config (4.0.0) 1 | com_content (4.0.0) 1 | com_contenthistory (4.0.0) 1 | com_cpanel (4.0.0) 1 | com_fields (4.0.0) 1 | com_finder (4.0.0) 1 | com_guidedtours (4.3.0) 1 | com_installer (4.0.0) 1 | com_joomlaupdate (4.0.3) 1 | com_languages (4.0.0) 1 | com_login (4.0.0) 1 | com_mails (4.0.0) 1 | com_media (3.0.0) 1 | com_menus (4.0.0) 1 | com_messages (4.0.0) 1 | com_modules (4.0.0) 1 | com_newsfeeds (4.0.0) 1 | com_plugins (4.0.0) 1 | com_postinstall (4.0.0) 1 | com_privacy (3.9.0) 1 | com_redirect (4.0.0) 1 | com_scheduler (4.1.0) 1 | com_tags (4.0.0) 1 | com_templates (4.0.0) 1 | com_users (4.0.0) 1 | com_workflow (4.0.0) 1 | com_wrapper (4.0.0) 1 |
3rd Party::

Modules :: Site ::
Core :: mod_articles_archive (3.0.0) 1 | mod_articles_categories (3.0.0) 1 | mod_articles_category (3.0.0) 1 | mod_articles_latest (3.0.0) 1 | mod_articles_news (3.0.0) 1 | mod_articles_popular (3.0.0) 1 | mod_banners (3.0.0) 1 | mod_breadcrumbs (3.0.0) 1 | mod_custom (3.0.0) 1 | mod_feed (3.0.0) 1 | mod_finder (3.0.0) 1 | mod_footer (3.0.0) 1 | mod_languages (3.5.0) 1 | mod_login (3.0.0) 1 | mod_menu (3.0.0) 1 | mod_random_image (3.0.0) 1 | mod_related_items (3.0.0) 1 | mod_stats (3.0.0) 1 | mod_syndicate (3.0.0) 1 | mod_tags_popular (3.1.0) 1 | mod_tags_similar (3.1.0) 1 | mod_users_latest (3.0.0) 1 | mod_whosonline (3.0.0) 1 | mod_wrapper (3.0.0) 1 |
3rd Party:: MOD_MYMOD (1.0) 1 |

Modules :: Admin ::
Core :: mod_custom (3.0.0) 1 | mod_feed (3.0.0) 1 | mod_frontend (4.0.0) 1 | mod_guidedtours (4.3.0) 1 | mod_latest (3.0.0) 1 | mod_latestactions (3.9.0) 1 | mod_logged (3.0.0) 1 | mod_login (3.0.0) 1 | mod_loginsupport (4.0.0) 1 | mod_menu (3.0.0) 1 | mod_messages (4.0.0) 1 | mod_multilangstatus (3.0.0) 1 | mod_popular (3.0.0) 1 | mod_post_installation_messages (4.0.0) 1 | mod_privacy_dashboard (3.9.0) 1 | mod_privacy_status (4.0.0) 1 | mod_quickicon (3.0.0) 1 | mod_sampledata (3.8.0) 1 | mod_stats_admin (3.0.0) 1 | mod_submenu (3.0.0) 1 | mod_title (3.0.0) 1 | mod_toolbar (3.0.0) 1 | mod_user (4.0.0) 1 | mod_version (3.0.0) 1 |
3rd Party::

Libraries ::
Core ::
3rd Party::

Plugins ::
Core :: plg_actionlog_joomla (3.9.0) 1 | plg_api-authentication_basic (4.0.0) 0 | plg_api-authentication_token (4.0.0) 1 | plg_authentication_cookie (3.0.0) 1 | plg_authentication_joomla (3.0.0) 1 | plg_authentication_ldap (3.0.0) 0 | plg_behaviour_compat (5.0.0) 1 | plg_behaviour_taggable (4.0.0) 1 | plg_behaviour_versionable (4.0.0) 1 | plg_content_confirmconsent (3.9.0) 0 | plg_content_emailcloak (3.0.0) 1 | plg_content_fields (3.7.0) 1 | plg_content_finder (3.0.0) 1 | plg_content_joomla (3.0.0) 1 | plg_content_loadmodule (3.0.0) 1 | plg_content_pagebreak (3.0.0) 1 | plg_content_pagenavigation (3.0.0) 1 | plg_content_vote (3.0.0) 0 | plg_editors-xtd_article (3.0.0) 1 | plg_editors-xtd_fields (3.7.0) 1 | plg_editors-xtd_image (3.0.0) 1 | plg_editors-xtd_menu (3.7.0) 1 | plg_editors-xtd_module (3.5.0) 1 | plg_editors-xtd_pagebreak (3.0.0) 1 | plg_editors-xtd_readmore (3.0.0) 1 | plg_extension_finder (4.0.0) 1 | plg_extension_joomla (3.0.0) 1 | plg_extension_namespacemap (4.0.0) 1 | plg_fields_calendar (3.7.0) 1 | plg_fields_checkboxes (3.7.0) 1 | plg_fields_color (3.7.0) 1 | plg_fields_editor (3.7.0) 1 | plg_fields_imagelist (3.7.0) 1 | plg_fields_integer (3.7.0) 1 | plg_fields_list (3.7.0) 1 | plg_fields_media (3.7.0) 1 | plg_fields_radio (3.7.0) 1 | plg_fields_sql (3.7.0) 1 | plg_fields_subform (4.0.0) 1 | plg_fields_text (3.7.0) 1 | plg_fields_textarea (3.7.0) 1 | plg_fields_url (3.7.0) 1 | plg_fields_user (3.7.0) 1 | plg_fields_usergrouplist (3.7.0) 1 | plg_filesystem_local (4.0.0) 1 | plg_finder_categories (3.0.0) 1 | plg_finder_contacts (3.0.0) 1 | plg_finder_content (3.0.0) 1 | plg_finder_newsfeeds (3.0.0) 1 | plg_finder_tags (3.0.0) 1 | plg_installer_folderinstaller (3.6.0) 1 | plg_installer_override (4.0.0) 1 | plg_installer_packageinstaller (3.6.0) 1 | plg_installer_urlinstaller (3.6.0) 1 | plg_installer_webinstaller (4.0.0) 1 | plg_media-action_crop (4.0.0) 1 | plg_media-action_resize (4.0.0) 1 | plg_media-action_rotate (4.0.0) 1 | plg_multifactorauth_email (4.2.0) 1 | plg_multifactorauth_fixed (4.2.0) 0 | plg_multifactorauth_totp (3.2.0) 1 | plg_multifactorauth_webauthn (4.2.0) 1 | plg_multifactorauth_yubikey (3.2.0) 1 | plg_privacy_actionlogs (3.9.0) 1 | plg_privacy_consents (3.9.0) 1 | plg_privacy_content (3.9.0) 1 | plg_privacy_message (3.9.0) 1 | plg_privacy_user (3.9.0) 1 | plg_quickicon_eos (4.4.0) 1 | plg_quickicon_downloadkey (4.0.0) 1 | plg_quickicon_extensionupdate (3.0.0) 1 | plg_quickicon_joomlaupdate (3.0.0) 1 | plg_quickicon_overridecheck (4.0.0) 1 | plg_quickicon_phpversioncheck (3.7.0) 1 | plg_quickicon_privacycheck (3.9.0) 1 | plg_sampledata_multilang (4.0.0) 1 | plg_schemaorg_blogposting (5.0.0) 1 | plg_schemaorg_book (5.0.0) 1 | plg_schemaorg_event (5.0.0) 1 | plg_schemaorg_jobposting (5.0.0) 1 | plg_schemaorg_organization (5.0.0) 1 | plg_schemaorg_person (5.0.0) 1 | plg_schemaorg_recipe (5.0.0) 1 | plg_system_accessibility (4.0.0) 0 | plg_system_actionlogs (3.9.0) 1 | plg_system_cache (3.0.0) 0 | plg_system_debug (3.0.0) 1 | plg_system_fields (3.7.0) 1 | plg_system_guidedtours (4.3.0) 1 | plg_system_highlight (3.0.0) 1 | plg_system_httpheaders (4.0.0) 1 | plg_system_jooa11y (4.2.0) 1 | plg_system_languagecode (3.0.0) 0 | plg_system_languagefilter (3.0.0) 0 | plg_system_log (3.0.0) 1 | plg_system_logout (3.0.0) 1 | plg_system_privacyconsent (3.9.0) 0 | plg_system_redirect (3.0.0) 0 | plg_system_remember (3.0.0) 1 | plg_system_schedulerunner (4.1) 1 | plg_system_schemaorg (5.0.0) 1 | plg_system_sef (3.0.0) 1 | plg_system_shortcut (4.2.0) 1 | plg_system_skipto (4.0.0) 1 | plg_system_stats (3.5.0) 0 | plg_system_task_notification (4.1) 1 | plg_system_webauthn (4.0.0) 1 | plg_task_check_files (4.1) 1 | plg_task_deleteactionlogs (5.0.0) 1 | plg_task_globalcheckin (5.0.0) 1 | plg_task_privacyconsent (5.0.0) 1 | plg_task_requests (4.1) 1 | plg_task_rotatelogs (5.0.0) 1 | plg_task_sessiongc (5.0.0) 1 | plg_task_site_status (4.1) 1 | plg_task_updatenotification (5.0.0) 1 | plg_user_contactcreator (3.0.0) 0 | plg_user_joomla (3.0.0) 1 | plg_user_profile (3.0.0) 0 | plg_user_terms (3.9.0) 0 | plg_user_token (3.9.0) 1 | plg_webservices_banners (4.0.0) 1 | plg_webservices_config (4.0.0) 1 | plg_webservices_content (4.0.0) 1 | plg_webservices_installer (4.0.0) 1 | plg_webservices_languages (4.0.0) 1 | plg_webservices_media (4.1.0) 1 | plg_webservices_menus (4.0.0) 1 | plg_webservices_messages (4.0.0) 1 | plg_webservices_modules (4.0.0) 1 | plg_webservices_newsfeeds (4.0.0) 1 | plg_webservices_plugins (4.0.0) 1 | plg_webservices_privacy (4.0.0) 1 | plg_webservices_redirect (4.0.0) 1 | plg_webservices_tags (4.0.0) 1 | plg_webservices_templates (4.0.0) 1 | plg_webservices_users (4.0.0) 1 | plg_workflow_featuring (4.0.0) 1 | plg_workflow_notification (4.0.0) 1 | plg_workflow_publishing (4.0.0) 1 |
3rd Party:: plg_editors_codemirror (6.0.0) 1 | plg_editors_tinymce (6.7.3) 1 |
Templates Discovered :: wrote:Templates :: Site :: cassiopeia (1.0) 1 |
Templates :: Admin :: atum (1.0) 1 |
You do not have the required permissions to view the files attached to this post.
Last edited by Martyn1 on Sat Feb 03, 2024 11:12 pm, edited 1 time in total.

Martyn1
Joomla! Apprentice
Joomla! Apprentice
Posts: 10
Joined: Thu Feb 03, 2022 10:19 pm

Re: Custom Module not working unless logged in

Post by Martyn1 » Sat Feb 03, 2024 11:10 pm

To add as well, it seems to work not logged in if I disable the login module or move my module to a test page where the login module is not active. I assume that I have a clash going on between the tokens for the two forms?

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2846
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: Custom Module not working unless logged in

Post by SharkyKZ » Mon Feb 05, 2024 6:33 am

Modules do not have endpoints. All pages in Joomla are handled by components. You need to either write a component for handling your request or at least use the AJAX component https://docs.joomla.org/Using_Joomla_Ajax_Interface.

Martyn1
Joomla! Apprentice
Joomla! Apprentice
Posts: 10
Joined: Thu Feb 03, 2022 10:19 pm

Re: Custom Module not working unless logged in

Post by Martyn1 » Mon Feb 05, 2024 10:09 pm

SharkyKZ wrote:
Mon Feb 05, 2024 6:33 am
Modules do not have endpoints. All pages in Joomla are handled by components. You need to either write a component for handling your request or at least use the AJAX component https://docs.joomla.org/Using_Joomla_Ajax_Interface.

Hi SharkyKZ, thankyou for taking the time to reply.

As you have probably worked out from my earlier posts this is all a steep learning curve for me and something I am enjoying so far. :eek:

Sorry for more questions but could you explain the endpoints bit? as I want to understand how that ties in with it working logged in but not when you are not logged into the frontend.

Secondly I have just been looking through the AJAX session module files from the link you kindly gave. As I have no experience with AJAX at all could you give some guidance as to how I would impliment this with the files I put the code for in my original post?

Many Thanks - Martyn

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2846
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: Custom Module not working unless logged in

Post by SharkyKZ » Tue Feb 06, 2024 8:00 am

All pages in Joomla are handled by components. You are currently submitting the form data to whatever component is set as home page. Whatever query parameters you use might conflict with the parameters used by the component, which can cause all sorts of issues. Which is why you should always use your own endpoint.
Anyways, the specific issue you're having is caused by broken form markup caused by this condition:

Code: Select all

if (!$result)
{
    return;
}
This leaves unclosed <form> which causes the fields of the adjacent form (possibly from Login module) to be submitted as well.

Martyn1
Joomla! Apprentice
Joomla! Apprentice
Posts: 10
Joined: Thu Feb 03, 2022 10:19 pm

Re: Custom Module not working unless logged in

Post by Martyn1 » Wed Feb 07, 2024 3:21 pm

Ok, so taking sharkyKZ's advice I have had a go at recreating my work but using Ajax. It has been difficult for my limited knowledge as it appears most examples are for older versions of joomla and this is my first time dabbling with ajax.

I settled on starting with this https://github.com/josedaboinv/Ajax-Sea ... mla-Module and after some editing have managed to get it to install on Joomla 5 and appear to work to a point.

The issue I am now having is that no matter what I put in the search I get the 'Sorry! No result for your search.' message. I get this even if I enter a number I know should return a result from the database. Can anyone advise where my limited knowledge has caused errors in the code or if I am way off.

mod_my_mod.php

Code: Select all

<?php

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Helper\ModuleHelper;

include_once __DIR__ . '/helper.php';

// Instantiate global document object
$doc = Factory::getDocument();

$js = <<<JS
(function ($) {
	
    $(document).on('click', 'input[type=submit]', function () {
	    var value   = $('input[name="data"]').val(),
            request = {
                    'option' : 'com_ajax',
                    'module' : 'my_mod',
                    'data'   : value,
                    'format' : 'raw'
                };
        $.ajax({
            type   : 'POST',
            data   : request,
	            
			beforeSend: function () {
				$(".search-result").append("Please Wait...<br>");
			},
		
			error:  function (response) { 
               		 $(".search-result").append('Error ajax: '+response.statusText );
			},
            success: function (response) {
                $('.search-result').html(response);
            }
        });
        return false;
    });
})(jQuery)
JS;

$doc->addScriptDeclaration($js);

require ModuleHelper::getLayoutPath('mod_my_mod');
helper.php

Code: Select all

<?php

defined('_JEXEC') or die;

use Joomla\CMS\Router\Route;
use Joomla\CMS\Factory;
use joomla\CMS\ContentHelperRoute;

class modMymodHelper
{
    public static function getAjax()
    {

        $input = Factory::getApplication()->input;
        $data  = $input->get('data');

        // Connect to database
        $db = Factory::getDbo();
        $query = $db->getQuery(true);


        // Build the query
        $query
            ->select('period')
            ->from($db->quoteName('#__gardnerperiod'))
            ->where($db->quoteName('first') . "<=" . $db->quote($data))
            ->andwhere($db->quoteName('last') . ">=" . $db->quote($data));

        $db->setQuery($query);
        $result = $db->loadResult();


        // Get output
        $output = null;

        if($output != null or empty($data))
        {
            $output .= '<h4><a> href="' . ContentHelperRoute::getArticleRoute($result) . '"></a></h4>';
        }

        else
        
        {
            $output = 'Sorry! No result for your search.'; 
        }


        return $output;
    }
}
default.php

Code: Select all

<?php 

defined('_JEXEC') or die;

use Joomla\CMS\Factory;

$document = Factory::getDocument(); //I add this piece of code
$document->addScript('//code.jquery.com/jquery-latest.min.js');  //I add this piece of code
?>

<form>
    <input type="text" name="data" />
    <input type="submit" value="Search" />
</form>
<div class="search-result"></div>

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2846
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: Custom Module not working unless logged in

Post by SharkyKZ » Thu Feb 08, 2024 9:43 am

This check doesn't make sense:

Code: Select all

if($output != null or empty($data))
$output is always null and when $data is null the result will also be null. You should check that $result is not empty here instead. Even better, add a check for $data before executing the query and return early:

Code: Select all

if (!$data)
{
    return 'Please enter a valid value...';
}

// Connect to database
$db = Factory::getDbo();
...
$result = $db->loadResult();

if ($result)
{
    return '<h4><a> href="' . ContentHelperRoute::getArticleRoute($result) . '"></a></h4>';
}

return 'Sorry! No result for your search.';

Martyn1
Joomla! Apprentice
Joomla! Apprentice
Posts: 10
Joined: Thu Feb 03, 2022 10:19 pm

Re: Custom Module not working unless logged in

Post by Martyn1 » Thu Feb 08, 2024 10:51 pm

Hi SharkyKZ,

Again Thankyou so much for your help.

I had to make some further adjustments to the code after doing the amendments you suggested above as I started to get "internal server error" returned, It appeared to have fixed one issue but then allowed to code to move on further to another bit I had got wrong.

However after some further tweeks I now have it up and working so to finish off this thread incase this helps anyone trying to do something similar below is the code I ended up with in the files which work in Joomla 5.0.2

mod_my_mod.php

Code: Select all

<?php

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Helper\ModuleHelper;

include_once __DIR__ . '/helper.php';

// Instantiate global document object
$doc = Factory::getDocument();

$js = <<<JS
(function ($) {
	
    $(document).on('click', 'input[type=submit]', function () {
	    var value   = $('input[name="data"]').val(),
            request = {
                    'option' : 'com_ajax',
                    'module' : 'my_mod',
                    'data'   : value,
                    'format' : 'raw'
                };
        $.ajax({
            type   : 'POST',
            data   : request,
	                //I add this piece of code
			beforeSend: function () {
				$(".search-result").append("Please Wait...<br>");
			},
			//I add this piece of code to check error
			error:  function (response) { 
               		 $(".search-result").append('Error ajax: '+response.statusText );
			},
            success: function (response) {
                $('.search-result').html(response);
            }
        });
        return false;
    });
})(jQuery)
JS;

$doc->addScriptDeclaration($js);

require ModuleHelper::getLayoutPath('mod_my_mod');
helper.php

Code: Select all

<?php

defined('_JEXEC') or die;

use Joomla\CMS\Factory;

class modMyModHelper
{
    public static function getAjax()
    {

        $input = Factory::getApplication()->input;
        $data  = $input->get('data');
      
      if (!$data)
        {
            return 'Please enter a valid value...';
        }

        // Connect to database
        $db = Factory::getDbo();
        $query = $db->getQuery(true);


        // Build the query
        $query
            ->select($db->quoteName('period'))
            ->from($db->quoteName('#__gardnerperiod'))
            ->where($db->quoteName('first') . "<=" . $db->quote($data))
            ->andwhere($db->quoteName('last') . ">=" . $db->quote($data));

        $db->setQuery($query);
        $result = $db->loadResult();

if ($result)
        {
            return "<a>" . $result . "</a>";
        }

return 'Sorry! No result for your search.';
    }
}
/tmpl/default.php

Code: Select all

<?php 

defined('_JEXEC') or die;

use Joomla\CMS\Factory;

$document = Factory::getDocument(); //I add this piece of code
$document->addScript('//code.jquery.com/jquery-latest.min.js');  //I add this piece of code
?>

<form>
    <input type="text" name="data" />
    <input type="submit" value="Search" />
</form>
<div class="search-result"></div>
my_mod.xml

Code: Select all

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="4.0" client="site" method="upgrade">
    <name>Your Module Name</name>
    <creationDate>07 February, 2024</creationDate>
    <author>Your Name</author>
    <authorUrl>https://Your Site</authorUrl>
    <copyright>Copyright (C) 2024 Your Cool Copyright. All rights reserved.</copyright>
    <license>GNU General Public License version 3, or later.</license>
    <version>1.0.0</version>
    <description>Your Module Description</description>
    <install>
		<sql>
			<file driver="mysql" charset="utf8">sql/install.mysql.sql</file>
		</sql>
	</install>
	<uninstall>
		<sql>
			<file driver="mysql" charset="utf8">sql/uninstall.mysql.sql</file>
		</sql>
	</uninstall>
	<update>
		<schemas>
			<schemapath type="mysql">sql/updates/mysql</schemapath>
		</schemas>
	</update>
    <files>
        <filename module="mod_my_mod">mod_my_mod.php</filename>
        <filename>mod_my_mod.xml</filename>
        <filename>helper.php</filename>
        <folder>tmpl</folder>
        <folder>sql</folder>
    </files>
</extension>

User avatar
ceford
Joomla! Hero
Joomla! Hero
Posts: 2537
Joined: Mon Feb 24, 2014 10:38 pm
Location: Edinburgh, Scotland
Contact:

Re: Custom Module not working unless logged in

Post by ceford » Fri Feb 09, 2024 9:28 am

Your module may be working but you are doing it all wrong! jQuery has been removed from Joomla - so try using plain JavaScript. Your query is vulnerable - you need to sanitise the input and bind to the query. This is a good read: https://www.dionysopoulos.me/book.html

Martyn1
Joomla! Apprentice
Joomla! Apprentice
Posts: 10
Joined: Thu Feb 03, 2022 10:19 pm

Re: Custom Module not working unless logged in

Post by Martyn1 » Fri Feb 09, 2024 10:17 am

ceford wrote:
Fri Feb 09, 2024 9:28 am
Your module may be working but you are doing it all wrong! jQuery has been removed from Joomla - so try using plain JavaScript. Your query is vulnerable - you need to sanitise the input and bind to the query. This is a good read: https://www.dionysopoulos.me/book.html
Hi Ceford thanks for the info. SharkyKZ hadn't mentioned there was an issue with using JQuery. will go and take a look at your link and try again........

User avatar
Pavel-ww
Joomla! Ace
Joomla! Ace
Posts: 1560
Joined: Tue Jun 30, 2020 12:17 pm

Re: Custom Module not working unless logged in

Post by Pavel-ww » Fri Feb 09, 2024 10:17 am

ceford wrote:
Fri Feb 09, 2024 9:28 am
jQuery has been removed from Joomla...
Hi. Just for clarification. It was removed from Joomla core, but exist in /media/vendor folder and can be called in template/component/module

Code: Select all

HTMLHelper::_('jquery.framework');


Post Reply

Return to “Joomla! 5.x Coding”