AJAX-enabled Smarty plugins

Posted by Dmytro Shteflyuk on under PHP

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 February 22nd, 2006 at 12:42 · Permalink

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

Michel
said on February 22nd, 2006 at 16:53 · Permalink

Hey very cool! keep up the good work!

said on February 22nd, 2006 at 17:04 · Permalink

really a great idea!

Leksi
said on February 28th, 2006 at 18:10 · Permalink

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

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

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

jack
said on March 7th, 2006 at 00: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 March 7th, 2006 at 06: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 March 15th, 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 March 15th, 2006 at 17:41 · Permalink

Unfortunately, this is not possible in current version.

chris
said on April 8th, 2006 at 14:11 · Permalink

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

baz
said on May 12th, 2006 at 15:34 · Permalink

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

vipin
said on May 16th, 2006 at 12:59 · Permalink

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

said on May 16th, 2006 at 13:06 · Permalink

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

said on May 16th, 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 August 27th, 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 August 31st, 2006 at 09: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 August 31st, 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 September 17th, 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 September 25th, 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 September 26th, 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 September 26th, 2006 at 23:28 · Permalink

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

Thiago
said on October 3rd, 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 October 9th, 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 October 10th, 2006 at 05: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 October 10th, 2006 at 05:07 · Permalink

thank you very much, you were very helpfull

said on October 16th, 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 October 19th, 2006 at 18:25 · Permalink

Hi, nice very nice page..!

Good luck !

German
said on October 26th, 2006 at 17:27 · Permalink

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

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

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

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

Wildhorse
said on November 7th, 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 November 7th, 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 November 7th, 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 November 28th, 2006 at 01: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 November 29th, 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 December 2nd, 2006 at 09:57 · Permalink

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

Eduardo Miranda
said on December 8th, 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 January 23rd, 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 January 23rd, 2007 at 22:50 · Permalink

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

said on February 14th, 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?

said on March 3rd, 2007 at 00: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 March 13th, 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 May 10th, 2007 at 12:58 · Permalink

AJAX pluginy pro Smarty…

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

dvs
said on May 11th, 2007 at 14:52 · Permalink

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

dnk
said on May 22nd, 2007 at 09:53 · Permalink

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

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

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

said on May 22nd, 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 May 28th, 2007 at 01: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

More comments: 1 2

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.