AJAX-enabled Smarty plugins

Feb 19
2006 01:49 (AJAX, Development, JavaScript, PHP) · Русский (93,945 views)

Today I’ve created simple AJAX-enabled plugins for Smarty. I don’t try to develop powerful reach-applications framework. I can give you only idea how to integrate AJAX-technology into Smarty. But if you have any offers how to improve anything I’ve described or if you just want to leave feedback please post you comments on my site.

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.

I decided to integrate Smarty with AJAX. There are three Smarty plugins has been created: ajax_update, ajax_call, ajax_form. Below all this plugins will be described.

ajax_update

This Smarty function can be used for update some parts of web-page.

Sample usage:

<a href="#" onclick="{ajax_update update_id='intro_content'
  function='update_intro' params='page=about'}">About</a>

Possible parameters:

  • url - URL for AJAX-query (when no URL was specified current one will be used)
  • method - query method (by default get, can be get or post)
  • update_id - ID of HTML element for update
  • function - function which will be called
  • params - URL-encoded parameters

ajax_call

This Smarty function can be used for call PHP function on server side and retrieve its output.

Sample usage:

<a href="#" onclick="{ajax_call function='calculate'
  params_func='calc_params' callback='calc_cb'}">Calculate</a>

Possible parameters:

  • url - URL for AJAX-query (when no URL was specified current one will be used)
  • method - query method (by default get, can be get or post)
  • function - function which will be called
  • params - URL-encoded parameters
  • callback - JavaScript function which will be called when query will be completed
  • params_func - JavaScript function used when you need custom parameters calculated on client side

ajax_form

This Smarty block can be used for submit Web-forms without post-back.

Sample usage:

{ajax_form method="post" id="form_register"}
Any form-element can be placed here
{/ajax_form}

Possible parameters:

  • url - URL for AJAX-query (when no URL was specified current one will be used)
  • method - query method (by default get, can be get or post)
  • params - URL-encoded parameters
  • id - form ID
  • callback - JavaScript function which will be called when query will be completed

Samples

These plugins are quite simple and I think everyone can create even better than mine. I’ve just wanted to show you idea how integration can be done. Working examples can be found here. Also you can download full sources.

69 Responses to 'AJAX-enabled Smarty plugins'

Subscribe to comments with RSS or TrackBack to 'AJAX-enabled Smarty plugins'.

1
said on 2006-02-21 at 9.48 am

[...] In my previous post I’ve described several simple AJAX plugins. Now I’ll show how to use one of them — ajax_form — in real applications. I think this is the most powerful plugin therefor I’ll dwell on it more elaborately. [...]

2
said on 2006-02-22 at 12.42 pm

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

3
Michel
said on 2006-02-22 at 4.53 pm

Hey very cool! keep up the good work!

4
said on 2006-02-22 at 5.04 pm

really a great idea!

5
Leksi
said on 2006-02-28 at 6.10 pm

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

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

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

6
jack
said on 2006-03-07 at 12.30 am

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?

7
said on 2006-03-07 at 6.31 am

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:

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");
8
Szenna
said on 2006-03-15 at 5.24 pm

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

thx

9
said on 2006-03-15 at 5.41 pm

Unfortunately, this is not possible in current version.

10
chris
said on 2006-04-08 at 2.11 pm

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

11
said on 2006-04-11 at 12.18 am

[...] AJAX-enabled Smarty plugins (tags: ajax smarty webdev) [...]

12
baz
said on 2006-05-12 at 3.34 pm

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

13
vipin
said on 2006-05-16 at 12.59 pm

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

14
said on 2006-05-16 at 1.06 pm

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

15
said on 2006-05-16 at 9.41 pm

[...] 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. [...]

16
said on 2006-05-20 at 1.55 pm

[...] AJAX-enabled Smarty plugins [...]

17
Milary
said on 2006-08-27 at 11.16 am

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

18
skonealone
said on 2006-08-31 at 9.13 am

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

19
skonealone
said on 2006-08-31 at 11.45 am

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

20
mr. ajax
said on 2006-09-17 at 4.26 pm

hi kpumuk,

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

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

thx

21
said on 2006-09-25 at 1.50 pm

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

onclick="{ajax_update url='test2.php' update_id='intro_content' function='update_intro3' params='page=`$param`&test=yeah'}"
22
gotmyredhaton
said on 2006-09-26 at 8.08 pm

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

23
Rafael Affonso
said on 2006-09-26 at 11.28 pm

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

24
Thiago
said on 2006-10-03 at 4.49 pm

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

25
Franco
said on 2006-10-09 at 3.52 pm

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?

26
said on 2006-10-10 at 5.04 am

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.

27
Franco
said on 2006-10-10 at 5.07 am

thank you very much, you were very helpfull

28
said on 2006-10-16 at 7.01 pm

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?

29
Mellisa
said on 2006-10-19 at 6.25 pm

Hi, nice very nice page..!

Good luck !

30
German
said on 2006-10-26 at 5.27 pm

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

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

31
Паклоннегг
said on 2006-10-27 at 10.30 am

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

32
Wildhorse
said on 2006-11-07 at 10.43 am

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.

33
said on 2006-11-07 at 10.45 am

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

34
Wildhorse
said on 2006-11-07 at 7.06 pm

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.

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'] ) );
}
35
Igor
said on 2006-11-28 at 1.54 am

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.

36
German
said on 2006-11-29 at 6.46 pm

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

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

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

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

37
said on 2006-12-02 at 9.57 am

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

38
Eduardo Miranda
said on 2006-12-08 at 11.02 pm

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

40
said on 2006-12-11 at 3.33 am

[...] Under normal circumstances, once you’ve passed your footer template to Smarty->display(), you’re done. There’s no going back without a refresh. Well, that was before Dmytro Shteflyuk wrote a sexy PHP library, aptly named smarty_ajax. [...]

41
Tiago
said on 2007-01-23 at 8.39 pm

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

42
Tiago
said on 2007-01-23 at 10.50 pm

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

43
said on 2007-02-14 at 4.16 pm

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?

44
said on 2007-03-03 at 12.33 am

Hi,

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

But I get the following error:

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

45
Philipp
said on 2007-03-13 at 11.59 am

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

46
said on 2007-05-10 at 12.58 pm

AJAX pluginy pro Smarty…

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

47
dvs
said on 2007-05-11 at 2.52 pm

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

48
dnk
said on 2007-05-22 at 9.53 am

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

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

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

49
said on 2007-05-22 at 10.18 am

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

update: function(update_id, url, method, params, callback) {
    var myAjax = new Ajax.Updater(
      update_id,
      url,
      {
        method: method,
        parameters: params,
        onComplete: callback
      });
  },

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

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>. Извиняюсь, это у меня ошибка в подсказке, и я ее сейчас исправлю.

50
Jesse
said on 2007-05-28 at 1.10 am

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

51
dnk
said on 2007-06-01 at 2.44 pm

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

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

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

52
said on 2007-06-01 at 3.07 pm

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

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

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);
    }
}
53
dnk
said on 2007-06-01 at 4.09 pm

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

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

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

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

54
said on 2007-06-01 at 4.43 pm

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

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

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);
      }
    }
  },

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

55
said on 2007-06-01 at 4.44 pm

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

56
said on 2007-06-01 at 5.38 pm

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

57
Alex
said on 2007-06-15 at 5.13 pm

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

{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>
58
Alex
said on 2007-06-19 at 8.55 pm

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

{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

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

But of course it does not work

59
Николай
said on 2007-08-14 at 7.15 pm

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

60
Александр
said on 2007-10-05 at 2.52 pm

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

61
Александр
said on 2007-10-06 at 3.15 pm

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

62
said on 2007-11-13 at 10.03 am

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

63
Vovanovski
said on 2007-11-30 at 3.15 pm

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

64
digitalapha
said on 2008-02-06 at 6.50 am

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.

65
said on 2008-03-26 at 2.54 pm

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

{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

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

66
fauzia
said on 2008-04-01 at 9.50 am

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?

67
fauzia
said on 2008-04-01 at 10.50 am

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:

{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

68
said on 2008-04-04 at 9.38 pm

Добрый день.

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

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

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

69
said on 2008-07-03 at 3.45 pm

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

:-(

Post a comment

You can use simple HTML-formatting tags (like <a>, <ul> and others). To format your code sample use <code lang="php">$a = "hello";</code> (allowed languages are ruby, php, yaml, html, csharp, javascript). Also you could use <code>$a = "hello";</code> and its syntax would not be highlighted. If you are not using <code> tag, replace < sign with &lt;.

Submit Comment

 
Copyright © 2005 - 2008, Dmytro Shteflyuk