How to register a user with jQuery Ajax in Joomla
If your are a Joomla developer sometimes you encounter a task which needs to produce jQuery Ajax call in order to register a new user at a Joomla CMS based site.
In this case this article will help you to implement this feature on your site.
So first open Joomla User Manager: Main menu -> Users -> User Manager, then click 'Options' button on the right.
Set 'Allow User Registration' to 'Yes'. Set 'New User Account Activation' parameter to 'none'.
Then add HTML form to your page.
Register User form sample HTML code:
Then create an empty file called: view.ajax.php and upload it to YOUR_SITE_HOME/components/com_content/views/article folder
Add the php code below into this file:
_registerNewUser( JFactory::getApplication()->input->post->get('form', NULL, 'ARRAY') );
break;
}
jexit();
}
public function _registerNewUser( $form ){
$username = $form[0]['value'];
$email = $form[1]['value'];
$password = $form[2]['value'];
$result = $this->_getNewAccount( $username, $email, $password );
$result = is_int($result) ? $result : 0;
//int - new user is registered, we've got its ID
//false - user exists with this login or email
echo json_encode( array('userId' => $result) );
jexit();
}
public function _getNewAccount( $username, $email, $password ){
JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_users/models', 'UsersModel');
$model = JModelLegacy::getInstance('Registration', 'UsersModel', array('ignore_request' => true));
$data = array(
'name' => $username,
'username' => $username,
'password1' => $password,
'password2' => $password,
'email1' => $email,
'email2' => $email
);
return $model->register($data);
}
}
?>
Then create a java script file with this JS script and add it to your page HEADER or just add it to your article php source:
Sample Register User form:
Click the button above to see how it makes a jQuery Ajax call and registers a new Joomla user.
Joomla Articles