Бібліотека FullAjax дозволяє оновлювати більше як один контейнер, завдяки реалізації в ній двох моделей запиту – один запит для одного блоку, та один – для декількох блоків. В плаґіні Add FullAjax (2011.01.10) ця можливість використовується для оновлення модуля “хлібних крихт”. Звичайно замість цього модуля можна підставити будь який інший, але лише один – це пов’язано з тим, що я ще не придумав як автоматизувати процес налаштування для оновлення декількох модулів/позицій.
Нижче маленька інструкція як налаштувати оновлення декількох модулів через Ajax.

Теорія, як це реалізовано в FullAjax.

Припустимо, що в нас є три блоки, які потрібно одночасно оновлювати з допомогою Ajax.

1
2
3
<div id="menu">Тут HTML код меню</div>
<div id="content">Тут HTML код вмісту</div>
<div id="baner_img">Тут HTML код картинки</div>

Для початку потрібно вказати для FullAjax які блоки потрібно оновлювати. Для цього додамо, в налаштування цієї бібліотеки, модель:

1
2
3
4
5
6
7
8
9
/* базове налаштування */
SRAX.Filter.add({url:'/', id:'content'});
SRAX.directLink();
/* модель */
SRAX.Model2Blocks['content'] = {
   'menu':'menu',
   'content':'content',
   'baner_img':'baner_img'
}

Для того, що це все щастя працювало, потрібно щоб вміст, який буде віддавати нам сервер, мав наступний вигляд:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- :ax:menu:begin: //-->
HTML код меню
<!-- :ax:menu:end: //-->
 
Все що знаходиться між цими блоками буде проігноровано при показі.
 
<!-- :ax:content:begin: //-->
HTML код вмісту
<!-- :ax:content:end: //-->
 
<!-- :ax:baner_img:begin: //-->
HTML код картинки банера
<!-- :ax:baner_img:end: //-->

Ось так просто, ми маємо змогу оновлювати декілька блоків одночасно.

Практика, як реалізувати оновлення декількох модулів в плаґіні Add FullAjax .

Маленька покрокова інструкція :)

1. Потрібно встановити шаблон “fullajax_tmpl”, якщо не встановлено.

2. В налаштуваннях плаґіну встановити оновлення модулів в ручну.

3. Далі, потрібно зайти в Module Manager та дізнатись позиції які бажаємо оновлювати. Для прикладу візьмемо: position-3, position-1, та user3.

4. Відкриваємо index.php нашого шаблону, та додаємо кожній цій позиції унікальний ідентифікатор(якщо цього не зроблено при створенні шаблону).
Приклад:

1
2
3
4
5
6
7
8
9
10
11
<div id="id-for-pos-three">
	<jdoc:include type="modules" name="position-3" />
</div>
	...
<div id="id-for-pos-user">
	<jdoc:include type="modules" name="user3" />
</div>
	...
<div id="id-for-pos-one">
	<jdoc:include type="modules" name="position-1" />
</div>

5. Заходимо в налаштування плаґіну, та в полі “Js code, parameters for FullAjax” додаємо модель для щойно створених блоків.

1
2
3
4
5
6
7
/* модель */
SRAX.Model2Blocks['forajax'] = {
   'id-for-pos-one':'id-for-pos-one',
   'id-for-pos-user':'id-for-pos-user',
   'id-for-pos-three':'id-for-pos-three',
   'forajax':'forajax'
}

forajax – це ідентифікатор вмісту.

6. Відкриваємо файл /templates/fullajax_tmpl/index.php та додаємо туди відсутні позиції.

1
2
3
4
5
6
7
8
9
10
11
<!-- :ax:id-for-pos-three:begin: //-->
	<jdoc:include type="modules" name="position-3" />
<!-- :ax:id-for-pos-three:end: //-->
 
<!-- :ax:id-for-pos-user:begin: //-->
	<jdoc:include type="modules" name="user3" />
<!-- :ax:id-for-pos-user:end: //-->
 
<!-- :ax:id-for-pos-one:begin: //-->
	<jdoc:include type="modules" name="position-1" />
<!-- :ax:id-for-pos-one:end: //-->

7. От і все :)

57s коментарів to “ Як оновлювати більше як один модуль з допомогою Ajax ”

  1. Володимир коментує:

    Два запитання:
    1) чи може воно якимось чином оновлювати заголовки (ті що jdoc:include type=”head”)
    2) якщо лічильники вставити в секцію forajax, то відвідування якої адреси вони будуть обліковувати – з #ajx чи без?
    Дякую.

    • Fedik коментує:

      Дві відповіді :)
      1. В плагіні це відбувається автоматично, але оновлюються лише: скрипти, стилі, заголовок.
      2. Тут все залежить від самого лічильника, як він перевіряє адресу. В останній версії плагіну(2011.03.08), якщо використовувати Google Analytics, то код лічильника потрібно додавати як звичайно, а в налаштуваннях плагіну встановити “I use Google Analytics” як “Yes” – тоді адреса буде реєструватись включаючи ‘#ajx/mypgae.html’ – інакше – лише те що йде до ‘#’

      • Володимир коментує:

        Заголовок-то оновлюється, а от чи то зі скриптами, чи то зі стилями не все гаразд, бо інші AJAX-компоненти перестають працювати – той же JComments, наприклад. Чи можна їх якось подружити між собою?

      • Fedik коментує:

        Інколи, можливий конфлікт з іншими скриптами (все передбачити не завжди можливо), тому кожен такий випадок потрібно розглядати окремо. Тут вже без базових знань JavaScript не обійтись. Раджу ще переглянути форум бібліотеки FullAjax.

  2. Meghraj коментує:

    Thanks for making this, it is a revolutionary plugin for joomla.
    But I have a problem, suppose we want to use it with one or more module position then it can get and show content there but suppose if the none of the module is present at that position for some of the page, then that place remains occupied by blank space.
    Is there any way to put “if else” conditions to solve this issue.
    Once this is solved, this plugin will be perfect.

    • Fedik коментує:

      Yes I think about this problem.
      But I don’t think whether “if else” is appropriate. I think the best way for fix this is to use some CSS+HTML tricks

  3. phing коментує:

    Hi there, I was confused with the last step.
    You said to go this /templates/fullajax_tmpl/index.php
    and type the code, but I can’t find that index.php anywhere.
    Help please?
    Though I can make the ajaz work but it’s not perfect, the header also included in the content when refreshed so I ended up has 2 header. The first one stay and acts as the main menu,scond one as the content that keep changing according the main menu.
    Can you advise me why and how this could happen and how to solve it?

    • Fedik коментує:

      Hi, maybe you forgot install a fullajax_tmpl template? ;-) if you want use this instruction then you need this template. Also you can use a default template .. but it will be little difficult.

      and about header, looks like you not added “id” where content displayed (as in the basic instruction)… but also can be something other

  4. Pali коментує:

    Hi, I set the ajax template and I got the respose of the desired 3 modules. But the menu ids and classes are different than original classes and ids. It causes appearance issues.

    I’m curious for the solution. Plíz help me.

    Thx:
    Pali

  5. Pali коментує:

    And thank you for your help.

  6. sixeyeco коментує:

    Thank you for the plugin. Joomla! desperately needs it.

    My loader has no animation, just text. I installed the tpl and edited the js to include a full url reference to a known spinner image. No luck. Any thoughts? Thank you again.

  7. popo коментує:

    Hi
    Thanks a lot for your plugin.
    I’m working on an “Artisteer” template and I did it by addind somes to where “component” and “message” are. and it works without removing my modules in same !

    but not for modules and positions.

    I’m not expert and I cann’t understand how to add my positions to FullAjax configuration.
    I know that in Joomla! templates, positions can be called by "jdoc":

    but in artisteer templates it looks like:

     
      position('banner2', 'art-nostyle');
      if ($view->containsModules('breadcrumbs'))
        echo artxPost($view->position('breadcrumbs'));
    	?&gt;

    and depends on other files such as: function.php

    also, semi-automatically option dose not works.

    can you help me.

    • Fedik коментує:

      with artister it litle bit difficult .. I not got good result when tried test …
      but try like:

      position('banner2', 'art-nostyle');
        if ($view->containsModules('breadcrumbs')) ?>
      <div id="some-id">
        <?php  echo artxPost($view->position('breadcrumbs')); ?>
      </div>
      <?php
  8. popo коментує:

    thanks a lot but, No! It did not work.
    as you know, artister uses it’s way (code) to find if any module IS in each position or not.
    this is all codes for my middle, (content) column:

    position('left', 'pmd-block'); ?>

    position('banner2', 'pmd-nostyle');
    ?>

    containsModules('breadcrumb'))

    echo artxPost($view->position('breadcrumb'));
    ?>

    positions(array('user1' => 50, 'user2' => 50), 'pmd-article');
    echo $view->position('banner3', 'pmd-nostyle');
    ?>

    hasMessages())
    echo artxPost('');
    echo '';
    ?>

    position('banner4', 'pmd-nostyle');
    echo $view->positions(array('user4' => 50, 'user5' => 50), 'pmd-article');
    echo $view->position('banner5', 'pmd-nostyle');
    ?>


    “forajax” works (only if “enable position update” set to ‘no’ or ‘manual’) but “brcb” not works (any way)!
    and your plugin parses Index.php of template for jdocs!
    here is the code:

    /**
    * Parse a document template and find modules position
    *
    * @return The parsed contents of the template
    */

    function _parseTemplate(){
    $matches = array();
    $tmplFile = file_get_contents(JPATH_THEMES.DS.$this->defTemplate.DS.'index.php');
    //if (preg_match_all('##iU', $tmplFile, $matches))
    if (preg_match_all('##iU', $tmplFile, $matches)) {
    $count = count($matches[1]);
    $needPos = array_keys($this->posParams);

    for ($i = 0; $i posInTemplate[$i] = array('block'=>$this->posParams[$name],'type'=>$type, 'name' => $name, 'attribs' => $attribs);
    }

    }
    }

    if I add codes with trister language to your “fullajax_templ/index.php”, it cann’t work.
    it needs function.php and other files in artister template folder!
    so semi automatic dose not works.

    can you tell me what is the code to add to “fullajax_templ/index.php” in this case?

    • popo коментує:

      all DIV and PHP removed! :)

      • Fedik коментує:

        yes, if you want try update a modules in a artister template you need set “enable position update” to ‘manual’ .. and then try configure fullajax_templ/index.php (as in article on this page) with hacking artister template ….
        “semi automatic” only for a standart joomla template ;) .. so with a frameworks and etc. it not work…

      • Fedik коментує:

        ah forgot :)
        in fullajax_templ/index.php need use standart joomla markup.
        if artister have

        position('banner4', 'pmd-nostyle');

        and if you want update a “banner4″ position then in fullajax_templ/index.php need add:

        <!-- :ax:there-div-id-in-template:begin: //-->
        	<jdoc:include type="modules" name="banner4" />
        <!-- :ax:there-div-id-in-template:end: //-->

        but before you need add some DIV with ID in a artister template for this position as I wrote before or about

Напишіть відгук

Ваша пошт@ не публікуватиметься. Обов’язкові поля позначені *

Можна використовувати XHTML теґи та атрибути: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>