AJAX проверка логина при регистрации
рейтинг: 5.5/10, голосов: 4
Для того чтобы сделать AJAX проверку понадобиться серверная часть PHP и клиентская JavaScript. Файлы ядра Joomla при этом затрагиваться не будут. Данный пример рассматривается на стандартном шаблоне Beez 2.0, поэтому он может не работать на других шаблонах. Но суть останется та же.
Серверная часть
Для проверки существования логина пользователя нужно делать запрос в БД. Для этого можно использовать свой контроллер. Так как этот пример будет рассматривать стандартную регистрацию, соответственно контроллер должен быть в компоненте «com_users». Создадим файл со следующим содержанием:
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.controller');
/**
* Класс для AJAX проверок
*
* @package Joomla.Site
* @subpackage com_users
* @since 1.7
*/
class UsersControllerCheck extends JController
{
/**
* Метод проверки имени пользователя
*/
public function name()
{
// проверка значения сессии
JRequest::checkToken('get') or jexit(JText::_('JINVALID_TOKEN'));
$name = JRequest::getVar('name', null, 'GET');
if ($name) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id');
$query->from('#__users');
$query->where('username = '. $db->quote($name));
$db->setQuery($query);
if ($db->loadResult()) {
die('логин занят');
} else {
die('логин свободен');
}
}
}
}
В этом файле собственно и будет происходить проверка логина пользователя. На вход должны поступать две переменные — имя пользователя и значение сессии. Остается написать клиентскую часть, которая будет отправлять эти данные.
Клиентская часть
В данном примере будет рассмотрен пример на mootools. Переопределите макет регистрации «components/com_users/views/registration/tmpl/default.php» в шаблоне и добавьте в него следующий JavaScript:
<script type="text/javascript">
<!--
window.addEvent("domready", function(){
document.id("jform_username").addEvent("blur", function(){
//проверка на корректность заполнения поля
//стандартная валидация добавляет class invalid,
//если поле заполнено неправильно.
var regex=/invalid/g;
if (regex.test(this.get('class')) || this.value.length < 2) return;
//получаем значение сессии из формы
//Элемент с именем сессии
//В данном случае это будет последний input в div-e
var form = this.getParent('form');
var inputs = form.getChildren('div input');
var s = inputs[inputs.length-1].name;
//удаляем элемент если установлен
if(this.getNext('span')) this.getNext('span').destroy();
//создаем новый элемент
var myElement = new Element('span', {'style':'margin-left:10px'});
myElement.inject(this, 'after');
//создаем AJAX запрос
var myRequest = new Request({
url: 'index.php?option=com_users&task=check.name&format=raw',
method: 'get',
onRequest: function(){
myElement.set('text', 'проверка логина');
myElement.addClass('ajax-loader');
},
onSuccess: function(responseText){
myElement.removeClass('ajax-loader');
myElement.set('text', responseText);
if (responseText == 'логин занят') {
myElement.getPrevious('input').addClass('invalid');
}
},
onFailure: function(){
myElement.set('text', 'Запрос не удался');
}
});
//посылаем запрос с данными
myRequest.send('name='+this.value+'&'+s+'=1')
})
})
//-->
</script>
Для «прелооадера» AJAX, загрузите какую-нибудь картинку в директорию «images» в шаблоне, например «ajax-loader.gif». И добавьте в свой файл стилей CSS, примерно следующие строки:
.ajax-loader {background:url(../images/ajax-loader.gif) no-repeat left;padding-left:20px;}
По желанию, этот пример можно подкорректировать под свои нужды шаблона, путем небольшой правки JS и CSS.
После этих манипуляций при регистрации пользователя, в форме регистрации должны добавиться изменения. А именно, после того как фокус уйдет с поля «Логин» в форме, данное поле не будет пустым и будет соответствовать требованиям стандартной JS проверки. Рядом с этим полем появиться новый элемент «span». В котором будет отображаться результат проверки логина пользователя.
Кинулся попробовать, но с ходу не получилось. Можно по подробнее описать действия?
пишет запрос не удался.
That is a good tip particularly to those fresh to the blogosphere.
Simple but very precise info… Many thanks
for sharing this one. A must read post!
Organic search site visitors іs distinct.
Ranking hіgh in the search engines іs tough.
Copyright © ALTA Language Services, Inc.
Подготовка сайта поддержки и посадочных страниц.
Проверить скорость загрузки Вашего сайта.
I pay a quick visit each day some sites and information sites
to read articles or reviews, however this web site provides feature based
articles.
Hi! I could have sworn I've been to this website before but after reading through
some of the post I realized it's new to me. Anyhow, I'm
definitely delighted I found it and I'll be book-marking and checking back often!
Hi everybody, here every one is sharing these kinds of familiarity, thus it's pleasant
to read this website, and I used to go to see this web site everyday.
Thank you for the good writeup. It in fact was a amusement account
it. Look advanced to more added agreeable from you!
However, how can we communicate?
Our high-class escorts supply a variety of solutions.
A?l attractive escort girls Paris аre discreet and expert.
These escort girls are incredible and damn attractive.
I do not even know how I ended up here, but I
thought this post was good. I don't know who you are but certainly you are going to a famous blogger
if you aren't already ;) Cheers!
Why users still make use of to read news papers when in this technological globe all
is available on web?
Hello, I log on to your blogs daily. Your writing style is witty, keep up the good work!
If you are going for best contents like I do, only go to see this web site every day because it provides feature contents, thanks
Si ya sabes qual tu negocio necesita el posicionamiento web,
y quieres saber c?mo trabajamos en Tu Posicionamiento
Web, haz click aqu? y rellena el formulario.
Thank you for sharing your info. I really appreciate your efforts and I
am waiting for your next write ups thanks once again.
Hello everyone, it's my first pay a visit at this website,
and article is in fact fruitful for me, keep up posting such content.
Greetings! Very useful advice within this article! It's the little changes that produce the largest changes.
Many thanks for sharing!
Hey there! Someone in my Myspace group shared this website with us so I came to take a look.
I'm definitely loving the information. I'm bookmarking and
will be tweeting this to my followers! Outstanding blog
and excellent design and style.
My brother suggested I might like this web site.
He was entirely right. This post truly made my day.
You cann't imagine simply how much time I had spent for
this info! Thanks!
Howdy very cool blog!! Man .. Excellent .. Wonderful ..
I will bookmark your blog and take the feeds also?
I'm happy to search out so many helpful information right here within the post,
we want develop more strategies in this regard, thanks for
sharing. . . . . .
Awesome! Its genuinely amazing paragraph, I have got much
clear idea regarding from this post.
I blog frequently and I seriously appreciate your content.
This great article has really peaked my interest.
I am going to bookmark your site and keep checking for new details about once a
week. I opted in for your Feed too.
Just desire to say your article is as amazing. The clearness in your post
is simply excellent and i can assume you are an expert on this subject.
Well with your permission allow me to grab your
RSS feed to keep up to date with forthcoming post.
Thanks a million and please carry on the gratifying
work.