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.
Most of Web-forms has variuos validation mechanisms. Simplest way is to process form on the server and parse result on client, where return data can be in following format:
1 2 | true;User was registered successfully;http://example.com/login/ false;Please enter your name;Entered passwords doesn't match |
Result string can be splitted on client and results can be shown in some part of page. Process function may looks like following (it’s part of smarty_ajax):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var SmartyAjax = { onSubmit: function(originalRequest) { var results = originalRequest.responseText.split(";"); if (results[0] == "true") { SmartyAjax.Messages.set(results[1], SmartyAjax.Messages.MT_WARNING) } else { SmartyAjax.Messages.clear(); SmartyAjax.Messages.setType(SmartyAjax.Messages.MT_ERROR); for (var i = 1; i < results.length; i++) { SmartyAjax.Messages.add(results[i]); } } } } |
This function uses several functions from SmartyAjax.Messages object which depends on following HTML elements:
1 2 3 4 | <div id="messages"> <p id="messages-title"></p> <ul id="messages-list"></ul> </div> |
To manage messages I’ve created Smarty template parts/warnings.tpl. You can use it in your PHP file in simple way:
1 2 3 4 | // is messages contains warning (or error) $t->assign('messages_warning', true); // array of messages $t->assign('messages', array('Please provide your account information')); |
Another thing we need to examine is message which informs user about processing AJAX request. There is SmartyAjax.Process object in the sample which has two methods: hide() and show() which can be used to hide and display message. They are depends on HTML-element with id=”ajax-process”. It’s necessary to add “position: absolute” style because of this messages will be shown in top-right corner of screen independing on scroll position.
ajax_form is simple to use:
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
Example can be found here, and full sources can be downloaded here.
Как можно совместить ajax_form и ajax_update ?
Задача – после сабмита формы, если есь ошибки заполнения с помощью ajax_update вписываем описания ошибок над элементами формы.
Если ошибок нет, на месте формы пишем “Success”
Схожи по смыслу вопрос:
Как заставить работать ajax_update по сабмиту формы (с передачей параметров/значений элементов формы) ?