How to log in 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 log in a user to a Joomla CMS based site. In this case this article will help you to implement this feature on your site.
Then add HTML form to your page. Log in User form sample HTML code: <form method="post" action="#" id="userForm"> <label for="username">Username</label> <input type="text" value="" name="username"> <label for="password">Password</label> <input type="password" value="" name="password"> <button id="login-user">Click to Log In</button> </form>
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:
<?php /** * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** * HTML Article View class for the Content component * * @package Joomla.Site * @subpackage com_content * @since 1.5 */ class ContentViewArticle extends JViewLegacy { function display($tpl = null) { $task = JRequest::getString('task'); switch( $task ){ case "registerNewUser": $this->_registerNewUser( JFactory::getApplication()->input->post->get('form', NULL, 'ARRAY') ); break; } jexit(); } public function _logInUser( $form ){ $options = array(); $credentials = array(); $credentials['username'] = $form[0]['value']; $credentials['password'] = $form[1]['value']; $result = JFactory::getApplication()->login($credentials, $options); $result = ($result) ? 1 : 0; //1 - logged in //0 - not logged in echo json_encode( array('loggedIn' => $result) ); jexit(); } } ?> 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: <script> jQuery(document).ready(function(){ jQuery('#login-user').click(function(e){ e.preventDefault(); form = jQuery('#userForm'); jQuery.ajax({ url: 'index.php?option=com_content&format=ajax&lang=en&view=article&task=loginUser&tmpl=component', type: 'post', dataType: 'html', data: { form: jQuery(form).serializeArray() }, async: true, success: function(response){ var result = jQuery.parseJSON(response); if ( result.loggedIn == 1 ) { //User logged in } else { //User not logged in } } }); }); }); </script>
Sample Log In User form:
Click the button above to see how it makes a jQuery Ajax call and logs in a Joomla user.

Joomla Articles