AJAX-плагины для Smarty

(JavaScript, PHP) · English (135,611 views)

Сегодня я написал простые плагины для Smarty, поддерживающие AJAX. Я не пытался разработать мощный фреймворк для веб-приложений,- просто хотелось дать идею, как можно интегрировать AJAX-технологию в Smarty. Но если у Вас есть любые предложения по улучшению системы, или Вы просто хотите отправить отзыв, оставьте комментарий на сайте.

На практике мне нужно несколько вещей от AJAX: обновить некоторые узлы DOM, отправить форму на сервер без перегрузки страницы, получить некоторые значения или выполнить вычисления на стороне сервера (возможно с использованием базы данных или других серверных ресурсов). Необходимо написать кучу кода JavaScript для реализации этих требований, даже несмотря на использование замечательной библиотеки JavaScript Prototype.

Я решил подружить Smarty и AJAX. Вот три плагина Smarty, которые были созданы: ajax_update, ajax_call, ajax_form. Ниже я опишу все эти плагины.

ajax_update

Эта функция Smarty может быть использована для обновления некоторых частей веб-страницы.

Пример использования:

1
2
<a href="#" onclick="{ajax_update update_id='intro_content'
 function='update_intro' params='page=about'}">О нас</a>

Возможные параметры:

  • url – URL для AJAX-запроса (если не указан URL, будет использован текущий)
  • method – метод запроса (по умолчанию get, может быть get или post)
  • update_id – ID элемента HTML для обновления
  • function – имя функции PHP, которая будет вызвана
  • params – URL-закодированные параметры

ajax_call

Эта функция Smarty может быть использована для вызова PHP-функции на стороне сервера и получения результатов ее вывода.

Пример использования:

1
2
<a href="#" onclick="{ajax_call function='calculate'
 params_func='calc_params' callback='calc_cb'}">Посчитать</a>

Возможные параметры:

  • url – URL для AJAX-запроса (если не указан URL, будет использован текущий)
  • method – метод запроса (по умолчанию get, может быть get или post)
  • function – имя функции PHP, которая будет вызвана
  • params – URL-закодированные параметры
  • callback – функция JavaScript, которая будет выполнена по завершении запроса
  • params_func – функция JavaScript, которая используется для вычисления параметров запроса на стороне клиента

ajax_form

Этот блок Smarty может быть использован для отправки веб-форм на сервер без перезагрузки страницы.

Пример использования:

1
2
3
{ajax_form method="post" id="form_register"}
Любой элемент формы может быть размещен здесь
{/ajax_form}

Возможные параметры:

  • url – URL для AJAX-запроса (если не указан URL, будет использован текущий)
  • method – метод запроса (по умолчанию get, может быть get или post)
  • params – URL-закодированные параметры
  • id – ID элемента формы
  • callback – функция JavaScript, которая будет выполнена по завершении запроса

Примеры

Эти плагины достаточно просты, и я думаю, что любой может создать получше моих. Я всего-лишь хотел показать идею, как можно произвести интеграцию. Рабочие примеры можно найти здесь. Кроме того, Вы можете скачать все исходники.

71 Responses to this entry

Subscribe to comments with RSS

said on 22.02.2006 at 12.42 · Permalink

Я еще не успел полностью ознакомиться с данной технологией, но она уже мне нравится по просмотренным примерам. Будем изучать.

Michel
said on 22.02.2006 at 16.53 · Permalink

Hey very cool! keep up the good work!

Leksi
said on 28.02.2006 at 18.10 · Permalink

Попробовала использовать вышепредложенные плагины. У меня довольно быстро все получилось, хоть до этого с Ajax я была знакома только в теории.
Пара замечаний:

  • в ajax_form было бы неплохо добавить возможность вешать обработчик на onsubmit, а так же устанавливать дополнительные аттрибуты тега <form>.
  • во всех плагинах, если приходит метод, отличный от POST или GET, по умолчанию устанавливать один из них, а не ту лабуду, которую туда можно подсовывать.

С нетерпением жду ajax_table :) Двигаешься в правильном направлении, так держать :)

jack
said on 07.03.2006 at 0.30 · Permalink

hey great job… just one thing… when used in IE, the page gets cached and does not refresh with new content. anyway to solve that?

said on 07.03.2006 at 6.31 · Permalink

To prevent IE from caching pages you can add to all url any random string (for example http://somehost.com/index.php?4397593847)
You can do this using JavaScript-function Math.rand() or PHP function mt_rand() or rand().

Another way is to set page headers to disable cache:

1
2
3
4
5
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
Szenna @
said on 15.03.2006 at 17.24 · Permalink

hi,
I have one question:
can i use/call class functions in the ajax_update and ajax_call?

thx

said on 15.03.2006 at 17.41 · Permalink

Unfortunately, this is not possible in current version.

chris
said on 08.04.2006 at 14.11 · Permalink

I don’t speak inglish, but let me say. Your plugin es really fantastic

baz
said on 12.05.2006 at 15.34 · Permalink

клевый ход , так держать

vipin
said on 16.05.2006 at 12.59 · Permalink

how can smarty section implemented using ajax.
i tryed but got some error.
please help

said on 16.05.2006 at 13.06 · Permalink

Hmm. I haven’t understood your problem. Can you provide code that you use?

said on 16.05.2006 at 21.41 · Permalink

[...] Bellow is the simple resources of Ajax Enabled Smarty plugins. I got from this site [http://kpumuk.info/ajax/ajax-enabled-smarty-plugins/]. this part of articles In my practice I need several things from AJAX: to update some nodes in DOM, to send forms without post-back, to retrieve some values or to perform server-side calculation (maybe using database or other server-side resources). It’s necessary to write tons of JavaScript to implement my requirements in spite of using cool JavaScript library Prototype. [...]

Milary @
said on 27.08.2006 at 11.16 · Permalink

This website is Great! I will recommend you to all my friends. I found so much useful things here. Thank you.

skonealone
said on 31.08.2006 at 9.13 · Permalink

hi

its greate job … well i am new to smarty and facing some problem, please help me as i am already using the smarty, now i dont want to change existing smarty setup, without changing the existing smarty configuration and i want to intigrate your AJAX-enabled Smarty plugins in my existing smarty configuration. so can u help me how do i intigrate ur plugin in it??? and as i tryed to intigrate i get syntax error called “unrecognized tag ‘ajax_form’” so pls help me in it.

let me know the steps..

thanx in advance n awaiting for ur reply

regards
-skonealone

skonealone
said on 31.08.2006 at 11.45 · Permalink

hi once again .. as i intigrated the smarty_ajax plugin but still me not able to post the variables to the action page..
when i click on submit button .. nothing is happening..
pls let me know where i am doing wrong..

regards
-skonealone

mr. ajax @
said on 17.09.2006 at 16.26 · Permalink

hi kpumuk,

how can i realize this: (look at the params, need this in smarty foreach)

1
onclick="{ajax_update url='test2.php' update_id='intro_content' function='update_intro3' params='page={$param}&test=yeah'}

thx

said on 25.09.2006 at 13.50 · Permalink

Hello, mr. ajax
This is standard Smarty future: you can use $variable inside {} in following way:

1
onclick="{ajax_update url='test2.php' update_id='intro_content' function='update_intro3' params='page=`$param`&test=yeah'}"
gotmyredhaton
said on 26.09.2006 at 20.08 · Permalink

hello kpumuk,
great work, thank you very much.

i found the callback isn’t working when using ajax_call.
can’t figure out why.

wouldn’t it be better to merge call and update?
at least, ajax_call with a callback to “update a div” would do it.

regards,
gotmyredhaton

Rafael Affonso
said on 26.09.2006 at 23.28 · Permalink

Ajax without XML????? I can’t understand, I need XML…

Thiago
said on 03.10.2006 at 16.49 · Permalink

Hi, congratulations for this plugun, its fantastic. But, how i can auto-load update intro in a div element?? onLoad event cannot load update_intro, only onclick is possible!!! Thanks

Franco
said on 09.10.2006 at 15.52 · Permalink

Hi, I want to use update to do that on some part, process a code and show the same smarty templated thing every 1 second.
Should pasting a line like {ajax_update update_id="intro_content"
function="update_intro" params="page=about"}
inside the javascript function that trigger timers work? Will that make it to recalculate the smarty templated code i wan to show or it’s already locked?

said on 10.10.2006 at 5.04 · Permalink

Hi Franco!
Just look at the examples. In chat.php and corresponding Smarty template you can find periodically updated part of page. Think it can help you.

Franco
said on 10.10.2006 at 5.07 · Permalink

thank you very much, you were very helpfull

said on 16.10.2006 at 19.01 · Permalink

Szenna’s comment inspired me to modify smarty_ajax to support calling object methods from ajax_call and ajax_update. I added an optional parameter “object” to both so you can call the function as a method of an object.

If you need this functionality, you can get it from http://logankoester.com/smarty_ajax/

@Kpumuk: Are you interested in incorporating my patch in the next release of smarty_ajax?

Mellisa @
said on 19.10.2006 at 18.25 · Permalink

Hi, nice very nice page..!

Good luck !

German @
said on 26.10.2006 at 17.27 · Permalink

Отличные плагины!
Спасибо тебе! Был бы очень рад увидеть еще плагины для смарти…

Это то, чего давно не хватало смарти.

Паклоннегг
said on 27.10.2006 at 10.30 · Permalink

идейа плагина очинь харошайа . пешы йищо

Wildhorse @
said on 07.11.2006 at 10.43 · Permalink

Your chat is really nice! Is it possible to use mysql instead of chat.txt. I tried to include a Database update … but it wont work.

said on 07.11.2006 at 10.45 · Permalink

Sure it’s possible. Can you show me your code? Will try to help you connect db.

Wildhorse @
said on 07.11.2006 at 19.06 · Permalink

I tried to modify the function add message … but i think i am on the wrong way … if i press send … nothing happens and no entry in db.

1
2
3
4
5
function add_message() {
  include_once( 'init.php' );
  $sql11 = 'INSERT INTO ! ( from_user, username, act_time, message) values( ?, ?, ?, ? )';
  $db->query( $sql11, array( CHAT_TABLE, '21', 'test', '456465', $_POST['message'] ) );
}
Igor @
said on 28.11.2006 at 1.54 · Permalink

Dear Kpumuk!

Your plugin is very useful.

A question about ajax_form:

I have a registration form. I have successfully made the ajax validation. I’d like to hide the form input fields upon successful registration and display a close button ( I am developing a prototype window enabled ajax application, the registration form is in inside a prototype window).

Thank you in advance.

German @
said on 29.11.2006 at 18.46 · Permalink

Пытаюсь прикрутить плагины к движку, который работает на смарти (koobi).
Строка
About

Вызывает ошибку

1
Fatal error: Smarty error: [in page/main_template.tpl line 120]: syntax error: unrecognized tag 'ajax_update' (Smarty_Compiler.class.php, line 580) in w:\home\forex.ru\www\class\tpl\Smarty.class.php on line 1095

Не в курсе, почему такая ошибка возникает?

said on 02.12.2006 at 9.57 · Permalink

Скорее всего, плагины не скопированы в каталог plugins, или ошибка с настройками путей. Посмотрите в моих примерах, там есть пример, как настроить поддержку нестандартного пути.

Eduardo Miranda @
said on 08.12.2006 at 23.02 · Permalink

I use this AJAX Smarty plugins, but i has problem with this characters: ó,ú,í,ú,á,ñ
when use this technology

Tiago
said on 23.01.2007 at 20.39 · Permalink

hi, congratulations the plugin is fantastic!!! about the back button on browser?
ps: I don’t speak english very well.

Tiago
said on 23.01.2007 at 22.50 · Permalink

problems with ã, ç, é, ô, í see here

said on 14.02.2007 at 16.16 · Permalink

Hi ,
I have a problem with ajax_call.Below is the code–

/Click for first details/

Now I want to pass certain parameters such as id=20,location_id=30, which is to be used by the testfunction for database query. How do I do it?

Igor @
said on 03.03.2007 at 0.33 · Permalink

Hi,

I’d like to use autosuggest on a smarty-ajax enabled page.

But I get the following error:

1
2
3
Error: Ajax.Updater is not a constructor
Source File: http://ctsz.osiris/admin/js/smarty_ajax/smarty_ajax.js
Line: 8

autosuggest can be found here.

Do you have any idea?

Thank you very much.
Igor

Philipp
said on 13.03.2007 at 11.59 · Permalink

Hi Dmytro,

very interesting smarty plugin you have made, but please, what do I have to do, if I want the form I submit to be displayed again onsubmit?

My form already includes highlighting of the fields with wrong data input, set by the php script. So all I want is to extend the form with your Smarty AJAX script for submitting (post) and getting the same form page.

Best regards
Philipp

said on 10.05.2007 at 12.58 · Permalink

AJAX pluginy pro Smarty…

AJAXové rozšíření pro šablonový systém Smarty nabízí Dmitrij Štefljuk

dvs
said on 11.05.2007 at 14.52 · Permalink

использую ajax_form
по моему работает не совсем корректно, а именно:
при наличии на форме нескольких элементов с типом submit значение всех их отправляется на сервер

dnk
said on 22.05.2007 at 9.53 · Permalink

Добрый день Дмитрий!
У меня проблема такая.
Использую ajax_update , но контент для обновления берется из яваскрипта такого рода:

Это новостная лента.
Так вот ajax_update его содержимое не выводит в

Любую статику или локальные данные выводит нормально!
Как быть?
Спасибо.

said on 22.05.2007 at 10.18 · Permalink

Здравствуйте
Чтобы выполнять JavaScript, который пришел в AJAX ответе, придется немного поправить smarty_ajax.js. Метод update, который сейчас выглядит так:

1
2
3
4
5
6
7
8
9
10
  update: function(update_id, url, method, params, callback) {
    var myAjax = new Ajax.Updater(
      update_id,
      url,
      {
        method: method,
        parameters: params,
        onComplete: callback
      });
  },

Нужно добавить опцию evalScripts:

1
2
3
4
5
6
7
8
9
10
11
  update: function(update_id, url, method, params, callback) {
    var myAjax = new Ajax.Updater(
      update_id,
      url,
      {
        method: method,
        parameters: params,
        onComplete: callback,
        evalScripts: true
      });
  },

Да, в последнем комментарии вы ошиблись при вставке кода, закрывающий тег — </code>. Извиняюсь, это у меня ошибка в подсказке, и я ее сейчас исправлю.

Jesse @
said on 28.05.2007 at 1.10 · Permalink

Is it possible to use this for uploading images and other files. Right now, it wont let me, everything else works great. Any help on this? Thanks

dnk
said on 01.06.2007 at 14.44 · Permalink

Добрый день!
Не помогло!

1
2
3
4
<h2>Глобальная новостная лента</h2>
<p>
  <script language="JavaScript1.2" src="http://img.lenta.ru/r/js/t111.js" type="text/javascript"> </script>
</p>

Этот скрипт всё равно не выводится функцией update_intro
Выводятся только слова – Глобальная новостная лента…

said on 01.06.2007 at 15.07 · Permalink

Добрый день, Вера
Да, действительно, так оно не будет работать в связи с тем, что подключение внешних скриптов не работает автоматически. Скорее всего придется разобрать response вручную с помощью регулярных выражений, и затем подключить файл со скриптом.

Вот по-быстрому набросал пример (s — это текст, который Вы получаете в результате AJAX-запроса (проверил в IE и Firefox).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var s = "<script src=\"http://img.lenta.ru/r/js/t111.js\" type=\"text/javascript\"><\/script>";

var fragment = '<script[^>]*src="([^"]*?)"[^>]*>([\u0001-\uFFFF]*?)<\/script>';
var matchAll = new RegExp(fragment, 'img');
var matchOne = new RegExp(fragment, 'im');

var scripts = s.match(matchAll) || [];
for (var i = 0, length = scripts.length; i < length; i++) {
    var matches;
    if (matches = scripts[i].match(matchOne)) {
        var script = document.createElement('SCRIPT');
        script.src = matches[1];
        script.type = 'text/javascript';
        document.body.appendChild(script);
    }
}
dnk
said on 01.06.2007 at 16.09 · Permalink

Не совсем понятно куда этот JSкрипт вставлять!
Я его вызываю и newsline.tpl

1
2
3
4
<h2>Глобальная новостная лента</h2>
<p>
<script language="JavaScript" type="text/javascript" src="newsline.js"></script>
</p>

который запускается Smatry из функции intro_update

Не выводит ничего
Я кстати не Вера! Меня Дмитрий зовут… :)

said on 01.06.2007 at 16.43 · Permalink

Ой, простите, попутал. email показался похожим :-) А Вы часом не из Котовска?

Тэкс, относительно скрипта. Придется чуток поправить smarty_ajax.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  update: function(update_id, url, method, params, callback) {
    var myAjax = new Ajax.Updater(
      update_id,
      url,
      {
        method: method,
        parameters: params,
        onComplete: callback || this.onUpdate
      });
  },

  onUpdate: function(originalRequest) {
    var result = originalRequest.responseText;

    var fragment = '<script[^>]*src="([^"]*?)"[^>]*>([\u0001-\uFFFF]*?)<\/script>';
    var matchAll = new RegExp(fragment, 'img');
    var matchOne = new RegExp(fragment, 'im');

    var scripts = result.match(matchAll) || [];
    for (var i = 0, length = scripts.length; i < length; i++) {
      var matches;
      if (matches = scripts[i].match(matchOne)) {
        var script = document.createElement('SCRIPT');
        script.src = matches[1];
        script.type = 'text/javascript';
        document.body.appendChild(script);
      }
    }
  },

Вроде бы должно помочь…

said on 01.06.2007 at 16.44 · Permalink

Кстати, тезка, может ICQ (107989380) — тогда решим Вашу проблему быстрее вместе :-)

said on 01.06.2007 at 17.38 · Permalink

то что искал. Спасибо.

Alex @
said on 15.06.2007 at 17.13 · Permalink

Привет!
Возможно ли решить такую задачу? Как-то заставить работать document.forms.poll_update.submit();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{ajax_form method="post" id="poll_update" url="index.php?p=news&amp;area=$area&amp;newsid=$newsid" callback="submit_av"}
...
...
...
{/ajax_form}

<script language="javascript">
function submit_av(originalResponse)
{ldelim}
    $("user_poll").innerHTML = originalResponse.responseText;
{rdelim}
</script>

<a href=# onclick="check()">VOTE</a>

<script language="javascript">
function check()
{ldelim}
     document.forms.poll_update.vote.value=6;
     document.forms.poll_update.submit();
{rdelim}
</script>
Alex @
said on 19.06.2007 at 20.55 · Permalink

Hey this is a great library, thanks very much.

Is there a way of getting smarty to process the output. For instance, in my HTML I have

1
2
3
{section name=i loop=$faItems}
  //build a table of faItems
{/section}

In my php I create the faItems array. I would like to be able to update this object remotely and re-display it. Can I do this?

I have tried

1
$t->assign('faItems', $faItems);

But of course it does not work

Николай @
said on 14.08.2007 at 19.15 · Permalink

Люди есть проблема! В FireFox 2.0.0.6 и Опера 9.23 РАБОТАЕТ ВСЕ замечательно! ( {ajax_update} )
А вот в ИЕ6 НЕТ. В чем может быть проблема? Плз.

Александр
said on 05.10.2007 at 14.52 · Permalink

А как через ajax_update обновить список select ?

Александр
said on 06.10.2007 at 15.15 · Permalink

В общем товарищи конечно без обид, но лучше используйте библиотеку xajax !
Под смарти затачивается на раз !

said on 13.11.2007 at 10.03 · Permalink

Дмитрий, а Вы не могли бы уделить немного времени и написать третью часть по использованию данных плагинах, но в этой статье более подробно описать принцип создания и взаимодействия…. если честно, уже столько времени бьюсь и не понимаю многих вещей…вроде и и понятно, но в тоже время не получается… Где то в комментах, некий гражданин выложил улучшенную версию с поддержкой ООП – а это именно то, что меня интересует… просто хочется увидеть мануал, где по этапам расписано, как и что применять…))) Ну если не сложно… Заранее спасибо.

Vovanovski
said on 30.11.2007 at 15.15 · Permalink

Привет Критик!
Такой вот вопросик по ajax_form:
у тебя в примерах форма сабмититься без перезагрузки страницы по нажатию на кнопку типа submit, а как сделать так, чтобы форма сабмитилась, если например внутри формы есть элемент select и должен происходить сабмит по onchange селекта? Если я пишу в селекте this.form.submit() то происходит перезагрузка страницы.

digitalapha @
said on 06.02.2008 at 6.50 · Permalink

I am having difficluty processing the ajax form
here. I m building a simple form, which display info in a table format like Name, Age, etc.

e.g. in the register.php example

{ajax_form method=”post” id=”myform”=”index.php?}



if $_POST()…
echo???

{/ajax_form}

is it possible in the $_POST {

instead of using the echo to put the value to an array, can we display a smarty template out e.g.

$smarty->display(outputgrid.tpl”

i.e. want to process the form, and then assign smart values, and then give back to a smarty template.

said on 26.03.2008 at 14.54 · Permalink

hello kpumuk,
great work, thank you very much.

i found the params isn’t working when using ajax_update.
can’t figure out why.

this code

1
2
3
4
5
{foreach from=$DB_RESULTS item=row_obj key=news_id }
<li>
<a href="#" onclick="{ajax_update update_id='intro_content'  function='view_news' params='page=news&&news_id='$row_obj->news_id' '}">read news</a>
</li>
 {foreachelse}

error display

1
Catchable fatal error: Object of class stdClass could not be converted to string in F:\Website\www\e-job_V2\resources\templates_c\%%3C^3CF^3CFBC54C%%news.tpl.php on line 43

$row_obj->news_id isn’t working

regards,
Nattaphon

fauzia @
said on 01.04.2008 at 9.50 · Permalink

hi,

I made a function in index.php getting list of products.
I tpl i called ajax-update function to get list of products in a box.It is giving js-error “Object SmartyAjax not found”.What is my mistake?

fauzia @
said on 01.04.2008 at 10.50 · Permalink

hi,

I solved previouse problem.Now I am using ajax_update without function to send params to certain url.I want to send cat_id which is I am getting in section of template page.here is code:

1
2
3
4
5
6
7
8
{section name=cat loop="$category"}    
 <tr>
 <td id="category_trid{$category[cat].id}" class="contenttext2">{$category[cat].id}
 <a href="#" onclick="{ajax_update update_id='productlist_div'   params='catid=`$category[cat].id`&page=product_list_ajax'}">{$category[cat].title}</a>
 </td></tr>
 {sectionelse}
 <tr><td>No category..</td></tr>
{/section}

I am not getting catid value but “$category[cat].id”.why?
but it is giving code text in params not its value

said on 04.04.2008 at 21.38 · Permalink

Добрый день.

Дмитрий, у меня вопрос. Есть форма калькулятора.

1
{ajax_form method="post" id="calculator" url="index.php" params="task=calculator&amp;param=$someparam"}

После submit возвращает на index.php, get параметры не передаются. Если в функции smarty_block_ajax_form убрать action=” – работает, но с перезагрузкой…
Чего не так?

said on 03.07.2008 at 15.45 · Permalink

Fatal error: Smarty error: unable to write to $compile_dir ‘/home/hosting/kpumuk.info/samples/smarty_ajax/resources/templates_c’. Be sure $compile_dir is writable by the web server user. in /home/hosting/kpumuk.info/samples/smarty_ajax/include/smarty/Smarty.class.php on line 1095

:-(

raj @
said on 17.09.2008 at 9.22 · Permalink
1
2
3
4
5
6
7
8
<SELECT NAME="sel_art" onchange="{ajax_update update_id="get_collections" function="show_collections" url="get_collections.php" params="artist_id=1"}">        
            {foreach from=$artist item=arti}           
                <OPTION VALUE="{$arti.id}">{$arti.artist_fname}</OPTION>
            {/foreach}


<SELECT NAME="sel_art" id="get_collections"></SELECT>
            </SELECT>
said on 16.02.2009 at 23.17 · Permalink

Hi,

i would like to know if it is possible to call a javascript function before the ajax request will start (to disable form elements or change the text of the button, eg)

Comments are closed

Comments for this entry are closed for a while. If you have anything to say – use a contact form. Thank you for your patience.