AJAX-enabled Smarty plugins

Posted by Dmytro Shteflyuk on under JavaScript, PHP · Русский (166,924 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:

1
2
<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:

1
2
<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:

1
2
3
{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.

71 Responses to this entry

Subscribe to comments with RSS

Паклоннегг
said on October 27, 2006 at 10:30 am · Permalink

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

Wildhorse @
said on November 7, 2006 at 10:43 am · 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 November 7, 2006 at 10:45 am · Permalink

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

Wildhorse @
said on November 7, 2006 at 7:06 pm · 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 November 28, 2006 at 1:54 am · 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 November 29, 2006 at 6:46 pm · 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 December 2, 2006 at 9:57 am · Permalink

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

Eduardo Miranda @
said on December 8, 2006 at 11:02 pm · Permalink

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

Tiago
said on January 23, 2007 at 8:39 pm · Permalink

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

Tiago
said on January 23, 2007 at 10:50 pm · Permalink

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

said on February 14, 2007 at 4:16 pm · 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 March 3, 2007 at 12:33 am · 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 March 13, 2007 at 11:59 am · 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 May 10, 2007 at 12:58 pm · Permalink

AJAX pluginy pro Smarty…

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

dvs
said on May 11, 2007 at 2:52 pm · Permalink

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

dnk
said on May 22, 2007 at 9:53 am · Permalink

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

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

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

said on May 22, 2007 at 10:18 am · 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 May 28, 2007 at 1:10 am · 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 June 1, 2007 at 2:44 pm · 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 June 1, 2007 at 3:07 pm · 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 June 1, 2007 at 4:09 pm · 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 June 1, 2007 at 4:43 pm · 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 June 1, 2007 at 4:44 pm · Permalink

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

said on June 1, 2007 at 5:38 pm · Permalink

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

Alex @
said on June 15, 2007 at 5:13 pm · 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 June 19, 2007 at 8:55 pm · 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 August 14, 2007 at 7:15 pm · Permalink

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

Александр
said on October 5, 2007 at 2:52 pm · Permalink

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

More comments: 1 2 3

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.