0 Пользователей и 1 Гость просматривают эту тему.
  • 0 Ответов
  • 367 Просмотров
*

antarey

  • Захожу иногда
  • 168
  • 1 / 0
Компонент на ajax
« : 08.12.2020, 10:39:58 »
Добрый день.
Помогите реализовать AJAX в компоненте.
За основу брал статьюhttps://docs.joomla.org/J3.x:Developing_an_MVC_Component/Adding_AJAX
Но ето не совсем то что мне нужно.
Задача - реализовать поиск по заданным параметрам и переход по пагинатору через AJAX
модель
Код
<?php

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

/**
 * Model to see the current entries
 * @author Antarey
 */
class AepetitionsModelPetitionslist extends JModelList
{
/**
* Method to auto-populate the model state.
* @param   string $ordering An optional ordering field.
* @param   string $direction An optional direction (asc|desc).
* @return  void
*/


protected function populateState( $ordering = null, $direction = null )
{
parent::populateState( $ordering, $direction );
$input = JFactory::getApplication()->input;
$params = JComponentHelper::getParams( 'com_aepetitions' );
$this->setState( 'list.start', $input->get( 'start' ) );

$this->setState( 'list.limit', JComponentHelper::getParams('com_aepetitions')->get('limit') );
//$this->setState( 'list.limit', $params->get( 'limit', 10 ) );
}

/**
* Method for receiving a request to view records
* @return JDatabaseQuery
*/
protected function getListQuery()
{

$input = JFactory::getApplication()->input;
$where_add = $input->get('where_add');
$where_sql = '';

if ($where_add)
{
$where_add_any_text = $where_add[0];
$where_add_created1 = $where_add[1];
$where_add_created2 = $where_add[2];
$where_add_published = $where_add[3];

if (!empty($where_add_published))
{
$where_sql = 't1.published = \'' . $where_add_published.'\'';
}
else
{
if (!empty($where_add_created1) && empty($where_add_created2))
{
$where_sql = 't1.created = \'' . JHtml::_('date', $where_add_created1, 'DATE_FORMAT_LC4').'\'';
}
else if (!empty($where_add_created1) && !empty($where_add_created2))
{
$where_sql = 't1.created >= \'' . JHtml::_('date', $where_add_created1, 'DATE_FORMAT_LC4').'\' AND t1.created <=\''. JHtml::_('date', $where_add_created2, 'DATE_FORMAT_LC4').'\'';
}
else
{
$where_sql = 'WHERE CONCAT_WS(t1.title,t1.introtext,t1.fulltext,u.name) LIKE \''.$where_add_any_text.'%\''    ;
}
}
}


$query = $this->getDbo()->getQuery( true );
$query->select( 't1.id,t1.title,t1.alias,t1.asset_id,t1.introtext,t1.fulltext,t1.created,t1.publish_down,t1.ordering,t1.metakey,t1.metadesc,t1.hits');
$query->select( 't1.published,t1.params,t1.catid,t1.vidpovid,t1.votescount,t1.pidpucu,t1.isconfirmed,t1.created_by, u.name as author_name,GROUP_CONCAT(up.name ) AS pidpysyname ' );
$query->from( '#__aepetitions as t1' );
$query->join( 'LEFT', '#__users AS u ON u.id = t1.created_by' );
$query->join( 'LEFT', '#__pidpysy AS p on p.aepetitions_id = t1.id' );
$query->join( 'LEFT', '#__users AS up on up.id = p.users_id' );
if ($where_sql)$query->where($where_sql );
$query->order('t1.created DESC');
$query->group( 't1.id');
//$query->setLimit($limit,$offset);
return $query;



}
//---------------------------------------------------------------------------------------------------------------------------------------------------------


}
просмотр view.json.php
Код
<?php

defined('_JEXEC') or die('Restricted access');

 
class AepetitionsViewPetitionslist extends JViewLegacy
{

function display($tpl = null)
{
$this->items = $this->get( 'Items' );
$this->pagination = $this->get( 'Pagination' );
$this->state = $this->get( 'State' );
aepetitionsSiteHelper::setDocument( JText::_( 'COM_AEPETITIONS' ) );

$user = JFactory::getUser();
$userId = $user->id;
$userName = $user->name;
$userGroup = $user->groups;
$dBtn = '';
$formAction ='';
if ($user->guest) {
$formAction=JRoute::_('index.php?option=com_users&view=login');
$btnAddPetitionCattion = JText::_( "COM_AEPETITIONS_NEED_AUTORIZE_ADD" );
} else {
$formAction = JRoute::_('index.php?option=com_aepetitions&view=addpetition');
$btnAddPetitionCattion = JText::_( "COM_AEPETITIONS_ADDPETITION" );
}


JText::script('COM_AEPETITIONS_STATE_ZBIR');
JText::script('COM_AEPETITIONS_STATE_ROZGLYAD');
JText::script('COM_AEPETITIONS_STATE_VIDPOVID');
?>
<div class="d-flex flex-column flex-fill" id="div-root" style="padding: 0px;padding-right: 20px;padding-bottom: 2px;padding-left: 20px;">
<?php echo '<input id="token" type="hidden" name="' . JSession::getFormToken(). '" value="1" />'; ?>

<div class="row d-flex flex-row flex-fill" id="row-top" style="box-shadow: 0px 9px 7px 1px;border-width: 0px;border-style: solid;border-bottom-width: 1.4px;border-bottom-style: solid;border-bottom-right-radius: 4px;border-bottom-left-radius: 4px;margin: 2px;">
<div class="col-2 d-flex d-md-flex justify-content-md-center align-items-md-center" id="col-img"><img class="img-fluid shadow-sm" src="components/com_aepetitions/assets/images/ePetitions.png"></div>
<div class="col-10 d-flex flex-column justify-content-md-center align-items-md-start" id="col-pepition-head" style="margin-bottom: 8px;">
<h3><?php echo JText::_( 'COM_AEPETITIONS' ); ?><br></h3>
<h4><?php echo JText::_( 'COM_AEPETITIONS_ORGANIZATION' ); ?><br></h4>

<form id="addPetition" action="<?php echo $formAction;?>" method="post">
<button class="btn btn-primary btn-lg border rounded" type="submit"><?php echo $btnAddPetitionCattion;?><br></button>
</form>

</div>
</div>

<div class="row" id="row-search" style="margin-top: 20px;">
<div class="col">
<div class="input-group">
<input type="text" style = "width: 84%" data-toggle="tooltip" data-bs-tooltip="" data-placement="bottom" id="input-search" name="input-search" placeholder="<?php echo JText::_( 'COM_AEPETITIONS_INPUT_SEARCH_PLACEHOLDER' ); ?>" title="<?php echo JText::_( 'COM_AEPETITIONS_INPUT_SEARCH_HINT' ); ?>">
<div class="input-group-append">
<div class="dropdown btn-group" role="group" id="opts-search" >
<button class="btn btn-outline-secondary dropdown-toggle" data-toggle="dropdown" aria-expanded="false" type="button" style="border-radius: 0;"></button>
<div class="dropdown-menu dropdown-menu-left">
<h6 class="dropdown-header"><?php echo JText::_('COM_AEPETITIONS_STATE');?></h6>
<a class="dropdown-item" href="#" data-val="1"><?php echo JText::_('COM_AEPETITIONS_STATE_ZBIR');?></a>
<a class="dropdown-item" href="#" data-val="2"><?php echo JText::_('COM_AEPETITIONS_STATE_ROZGLYAD');?></a>
<a class="dropdown-item" href="#" data-val="3"><?php echo JText::_('COM_AEPETITIONS_STATE_VIDPOVID');?></a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#" data-val="4"><?php echo JText::_('COM_AEPETITIONS_DATA_Z_PO');?></a>
</div>
</div>

<button class="btn btn-outline-secondary" id="btn-search-clear" type="button" style="display: none;" onclick="this.style.display = 'none';location.reload();return false;" title="<?php echo JText::_('COM_AEPETITIONS_CLEAR_SEARCH');?>">
<i class="fa fa-search-minus" style="text-align: center;font-size: 22px;"></i>
</button>

<button class="btn btn-outline-secondary" id="btn-search" type="button" disabled="">
<i class="fa fa-search" style="text-align: center;font-size: 22px;"></i>
</button>
</div>
</div>
</div>
</div>

<div id="item-data" class="container-fluid" style="margin-top: 10px;">
<?php
parent::display( $tpl );
?>
</div>
</div>

<?php

}
}
шаблон
Код
<?php
/** @var $this AepetitionsViewPetitionslist */
defined( '_JEXEC' ) or die; // No direct access
$needvotes = JComponentHelper::getParams('com_aepetitions')->get('needvotes');
$leftvotes ='';
$status = '';



?>

<?php foreach ( $this->items as $item ):

if (new DateTime() > new DateTime($item->publish_down))
{
$leftvotes = JText::_( 'COM_AEPETITIONS_LEFTVOTES_DOWN');
}
else $leftvotes = date_diff( new DateTime($item->publish_down), new DateTime())->days;


switch ($item->published) {
case 1:
$status = JText::_( 'COM_AEPETITIONS_STATE_ZBIR');
break;
case 2:
$status = JText::_( 'COM_AEPETITIONS_STATE_ROZGLYAD');
break;
case 3:
$status = JText::_( 'COM_AEPETITIONS_STATE_VIDPOVID');
break;
case 4:
$status = JText::_( 'COM_AEPETITIONS_STATE_CANCELED');
break;
}
?>

<div class="row" id="row-items" style="border-radius: 4px;padding: 4px;border-width: 0.1px;border-style: solid; margin-top: 10px; border-color: rgb(206 212 218)">
<div class="col-8 d-flex flex-column" id="col-items-left">
<div id="alias" class="text-break"><p><?php echo $item->alias; ?></p></div>
<a id="introtext" class="text-break" href="<?php echo JRoute::_( 'index.php?option=com_aepetitions&view=petitionitem&id=' . $item->id  ); ?>" style="font-size: 20px;"><?php echo $item->introtext; ?></a>
<div id="created" class="text-break"><p><?php echo JText::_( 'COM_AEPETITIONS_CREATION_DATE').' <b>'.JHtml::_('date', $item->created, 'd-m-Y').'</b>';?></p></div>
</div>
<div class="col-4 d-flex flex-column" id="col-items-right">
<div id="votescount" class="text-break"><?php echo JText::_( 'COM_AEPETITIONS_VOTES').': <b>'.$item->votescount.'</b>';?></div>
<div id="needvotes" class="text-break"><?php echo JText::_( 'COM_AEPETITIONS_NEEDVOTES').': <b>'.$needvotes.'</b>';?></div>
<div id="published" class="text-break"><?php echo JText::_( 'COM_AEPETITIONS_STATE').': <b>'.$status.'</b>';?></div>
<div id="leftvotes" class="text-break"><?php echo JText::_( 'COM_AEPETITIONS_LEFTVOTES').' <b>'. $leftvotes .'</b>';?></div>
</div>
</div>
<?php endforeach; ?>

<div class="row" id="row-pagination" style="margin: 10px;margin-right: 4px;margin-left: 4px;margin-bottom: 0px;">
<div class="col" id="pagination-col">
<?php echo $this->pagination->getPagesLinks(); ?>
</div>
</div>

контроллер
Код
<?php
// No direct access
defined( '_JEXEC' ) or die;

/**
 * Controller
 * @author Antarey
 */
class AepetitionsControllerPetitionslist extends JControllerLegacy
{

}
controller.php
Код
<?php
defined( '_JEXEC' ) or die; // No direct access

/**
 * Default Controller
 * @author Antarey
 */
class AepetitionsController extends JControllerLegacy
{
    public function checkTokens()
    {
        if (!JSession::checkToken('get'))
        {
            echo new JResponseJson(null, JText::_('JINVALID_TOKEN'), true);
        }
        else
        {
            parent::display();
        }
    }
/**
* Method to display a view.
* @param bool $cachable
* @param array $urlparams
* @return JControllerLegacy
*/
function display( $cachable = false, $urlparams = array() )
{

$this->getView('PetitionsList', 'json');
$this->input->set('view', 'PetitionsList');
//$this->default_view = 'PetitionsList';
parent::display( $cachable, $urlparams );
return $this;
}

/**
* Call AJAX method
* @throws Exception
*/
public function getAjax()
{
$input = JFactory::getApplication()->input;
$model = $this->getModel( 'ajax' );
$action = $input->getCmd( 'action' );
$reflection = new ReflectionClass( $model );
$methods = $reflection->getMethods( ReflectionMethod::IS_PUBLIC );
$methodList = array();
foreach ( $methods as $method ) {
$methodList[] = $method->name;
}
if ( in_array( $action, $methodList ) ) {
$model->$action();
}
exit;
}
}
При открытии страницы все нормально, а потом проблемы:
при поиске или пагинации подгружается вся страница а не только default.php
получаю две ошибки
на уровне сервера
Warning: Invalid argument supplied for foreach() in D:\laragon\www\components\com_aepetitions\views\petitionslist\tmpl\default.php on line 12
ну и на клиенте
ep?start=5:278 Uncaught TypeError: Cannot read property 'limitstart' of undefined
    at HTMLAnchorElement.onclick (ep?start=5:278)
onclick @ ep?start=5:278
Помогите доделать, ткните носом что не так делаю
Может есть где-то статейка как реализовать AJAX в компоненте а не только поиск
Чтобы оставить сообщение,
Вам необходимо Войти или Зарегистрироваться
 

ajax загрузка компонента на странице материала К2

Автор Divn

Ответов: 0
Просмотров: 520
Последний ответ 13.01.2023, 15:05:52
от Divn
При срабатывании ajax появляетсся div id="system-message-container"

Автор androv77

Ответов: 1
Просмотров: 453
Последний ответ 17.11.2022, 11:50:42
от androv77
Не устанавливается компонент через панель управления

Автор Margarita

Ответов: 1
Просмотров: 396
Последний ответ 15.06.2022, 12:28:18
от Margarita
Компонент Yandex.Market XML

Автор valery63

Ответов: 2
Просмотров: 450
Последний ответ 06.02.2022, 15:38:36
от valery63
После обновления FOF 4 перестал работать компонент JCH optimize

Автор polezniy

Ответов: 1
Просмотров: 471
Последний ответ 05.01.2022, 10:45:04
от polezniy