Bootstrap Example

Ajax Login form using PHP and MySQL

Today I would like to show you Ajax login functionality implementation using PHP and MySQL. We gonna use the MySQL PDO driver in this tutorial. PDO has a much nicer interface, you will end up being more productive, and write safer and cleaner code.

Create Ajax Login Form

Login Form

Create a file called login_form.php with the following code.

 

Login Page

Login

Database Details

This tutorial assumes that you have the following user table structure in your database. For the sake of the example script, I have provided an insert query with test data.

CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `first_name`, `last_name`, `email`, `password`, `date_added`) VALUES (1, 'Arjun', 'PHP', '[email protected]', '$2y$10$8mVSGv/bIGgcvCikXBPfTu7HfXMl3jqfiirtQGyRwV5bvOzNGmmLG', '2017-10-12 18:09:10');

You can generate password hash by using password_hash() function, example echo password_hash(«password», PASSWORD_DEFAULT); .

Config.php

After importing the above table into your database. Create a file called config.php, where you gonna save information about MySQL Database configuration, you can use this file to save other config details too.

Login

Create a file called login.php with the following code. This file will handle the login requests, It will validate user details against the database. Upon valid and successful login, it will start the user session, otherwise, it will throw the appropriate error message.

 if (empty($_POST['password'])) < $error[] = "Password field is required"; >if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) < $error[] = "Enter Valid Email address"; >if (count($error) > 0) < $resp['msg'] = $error; $resp['status'] = false; echo json_encode($resp); exit; >$statement = $db->prepare("select * from users where email = :email"); $statement->execute(array(':email' => $_POST['email'])); $row = $statement->fetchAll(PDO::FETCH_ASSOC); if (count($row) > 0) < if (!password_verify($_POST['password'], $row[0]['password'])) < $error[] = "Password is not valid"; $resp['msg'] = $error; $resp['status'] = false; echo json_encode($resp); exit; >session_start(); $_SESSION['user_id'] = $row[0]['user_id']; $resp['redirect'] = "dashboard.php"; $resp['status'] = true; echo json_encode($resp); exit; > else

secure.php

Create a file called secure.php file with the following code. On successful login, we will redirect the user to this page. Only authenticated users can access this page. If unauthorized users try to access this page, users will forcefully be redirected to the login page.

logout.php

Create a file called logout.php and put the below code in the file.

Once everything is in place head over to the browser with http://localhost/login_form.php you should get output something like the below image

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face — we are here to solve your problems.

Источник

Login with ajax in PHP, MySQL

The Ajax Login form is very useful to sign in quickly to the database without refreshing the web page. So. It is frequently used in most web applications to make their registration form userfriendly & attractive.

In this tutorial, I have shared some simple steps to create the login/sign-in form using jquery Ajax in PHP & MySQL.

Steps to Create Login Form using Ajax, PHP

Now, Let’s start the coding to create the Ajax login form with the following simple steps –

1. Create Ajax Login Directory

First of all, You should create the following directory structure to build the login form.

source-code/ |__database.php |__login.php |__dashboard.php |__user-details.php |__logout.php |__login.js

2. Create a Database Connection

3. Create a Login Form

To create the Login form UI, You have to follow the following points –

  • Create a basic HTML structure
  • Include the bootstrap5 CDN
  • Create a form with id ‘loginForm’
  • Also, create some input fields for emailAddress, password & submit button.
  • Include the jQuery CDN
  • Include the login.js
        

Ajax Login Form

4. Send Login Request with Ajax

Now, We have to write Ajax code to process the login credential to the PHP script. So, create a login.php and write the jquery Ajax code. This code will execute when the user submits the form after filling out their registration.

To write an Ajax code for login, you have to follow the following points –

  • Apply the submit event on the form id ‘loginForm’
  • Define the e.preventDefault to prevent the form from the reloading
  • Implement the next steps within the $.ajax()
  • define the form method post
  • define the PHP file path – login.php
  • also, serialize the input data using serialize() method
  • define the success to get the success response
  • redirect to the dashboard.php using indow.location.href
$(document).on('submit','#loginForm',function(e) < e.preventDefault(); $.ajax(< method:"POST", url: "login.php", data:$(this).serialize(), success: function(data)< if(data === 'success') < window.location.href="dashboard.php"; >else < $('#msg').html(data); $('#loginForm').find('input').val('') >>>); >);

5. Get Login Response with PHP & MySQL

Now, We have to check the login credential in the database, So, create a login.php file and write the PHP code. The code of this file will run while the Ajax code will be executed and sent to the post request.

To process login credential, you have to write PHP code with the following points-

  1. Include the database.php file
  2. and assign connection variable $conn to the $db
  3. Create a custom function loginUser() with two parameters $db and $userData.
  4. write a MySQLi query to insert data into the database,
  5. And then call the created function loginUser()
query($query); if($result->num_rows > 0) < session_start(); $_SESSION['userId'] = $emailAddress; echo "success"; >else < echo "Wrong email and password"; >> else < echo "All Fields are required"; >>

6. Create a Dashboard with User Details

After login, you need to redirect to the dashboard. So You can get the logged-in user details on the dashboard page.

     

Welcome to Dashboard

Logout

7. Get Logged in User Details

You can use the following code to get the logged in user details from the database.

File Name – user-details.php

 function getUserbyId()< global $db; $userId = $_SESSION['userId']; $data = []; $query = "SELECT firstName, lastName FROM ".tableName; $query .= " WHERE emailAddress = '$userId'"; $result = $db->query($query); if($result->num_rows > 0) < $data = $result->fetch_assoc(); > else < header("location:index.php"); >return $data; >

8. Create Logout in PHP

To logout, You need to destroy session and redirected to the login page.

9. Test Ajax Login Yourself

Now, You can text the Ajax login form by opening it in the web browser.

When you open the login form will get the email address and Password fields

After that Enter the login credential and submit the form. after that, you will be logged in successfully without reloading the web page and redirected to the dashboard page.

Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I’m a Software Engineer. I have been working in the Web Technology field for 4 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Источник

Login page with jQuery and AJAX

A Login page is one of the basic requirements when creating a registration based website where the user can register to the website and sign in to its account to manage.

In this case, you can use AJAX to create a user-friendly login page.

With AJAX you can directly check the entered username and password are correct or not in MySQL database without reloading the whole page.

If the user is registered then redirect the user to a home page otherwise display an error.

Login page with jQuery and AJAX

Contents

1. Table structure

I am using users table in the tutorial example.

CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `password` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a new config.php file for the database connection.

Completed Code

Данный скрипт сравнивает то, что ввел пользователь с данными который хранятся в БД, и если пользователь ввел все верно возвращает «ok» Ajax скрипту, в противном случае возвращает «error».

И собственно Ajax скрипт (с помощью фреймворка JQuery)

  //При каждом нажатии клавиши в input элементе $('#a_login').keyup(function() < //Берем данные с input Элемента login_user = $('#a_login').val(); $.ajax(< url : 'authorization.php', type : 'POST', //метод запроса //Передаем введенные пользователем данные в PHP скрипт data : , //если PHP отработал верно success : function(xhr, data, textStatus) < if(xhr == 'ok')< //Если логин введен верно $('#a_login').css('box-shadow','0 0 10px rgba(0, 255, 0, 1)'); $('#a_login').css('-webkit-box-shadow','0 0 10px rgba(0, 255, 0, 1)'); $('#a_login').css('-moz-box-shadow','0 0 10px rgba(0, 255, 0, 1)'); >else if(xhr == 'error') < //Если такого логина не существует $('#a_login').css('box-shadow','0 0 10px rgba(255, 0, 0, 1)'); $('#a_login').css('-webkit-box-shadow','0 0 10px rgba(255, 0, 0, 1)'); $('#a_login').css('-moz-box-shadow','0 0 10px rgba(255, 0, 0, 1)'); >//При какой то ошибке else alert('Ошибка авторизации!'); >, //В случае, если PHP скрипт отработал с ошибкой error : function(xhr, textStatus, errorObj)< alert('Произошла критическая ошибка!'); >, >); >);

Источник

Читайте также:  How to take array input using JavaScript
Оцените статью