AJAX-enabled Smarty plugins

Posted by Dmytro Shteflyuk on under JavaScript, PHP · Русский (140,912 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 6, 2007 at 3:15 pm · Permalink

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

said on November 13, 2007 at 10:03 am · Permalink

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

Vovanovski
said on November 30, 2007 at 3:15 pm · Permalink

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

digitalapha @
said on February 6, 2008 at 6:50 am · 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 March 26, 2008 at 2:54 pm · 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 April 1, 2008 at 9:50 am · 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 April 1, 2008 at 10:50 am · 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 April 4, 2008 at 9:38 pm · 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 July 3, 2008 at 3:45 pm · 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 September 17, 2008 at 9:22 am · 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 February 16, 2009 at 11:17 pm · 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)

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.