Bootstrap Example

Registration Form using Ajax, PHP & MySQL

If you want to create a registration form that will not reload after submitting the registration details. Then you should make the ajax registration form with PHP & MySQL.

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

In this tutorial, I have shared some simple steps to create the registration/signup form using jquery ajax in PHP & MySQL. Once you learn it you can create any type of other registration forms.

Steps to Create Ajax Registration Form with PHP & MySQL

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

Читайте также:  Java lang string cannot be cast to java lang enum

1. Create Registration Form Directory Structure

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

source-code/ |__database.php |__ajax-script.php |__php-script.php |__index.php |

2. Create MySQL Table

Now, Create a MySQL Database –

Database Name – codingstatus

CREATE DATABASE codingstatus

After that create a table in the database ‘codingstatus’

CREATE TABLE `users` ( `id` int(10) NOT NULL AUTO_INCREMENT, `firstName` varchar(50) DEFAULT NOT NULL, `lastName` int(50) DEFAULT NOT NULL, `gender` int(10) DEFAULT NOT NULL, `emailAddress` int(50) DEFAULT NOT NULL, `password` int(20) DEFAULT NOT NULL );

3. Connect PHP to MySQL Database

Now, You have to connect PHP to the MySQL database with the following code

4. Create a Registration Form UI

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

  • Create a basic HTML structure
  • Include the bootstrap5 CDN
  • Create a form with id ‘registrationForm’
  • Also, create some input fields for firstName, lastName, gender, email & submit button.
  • Include the jQuery CDN
  • Include the ajax-script.js
        

Ajax Registration Form

Male Female

5. Write ajax code for Registration

Now, We have to write ajax code to process the user Input to the PHP script. So, create a ajax-script.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 registration, you have to follow the following points –

  • Apply the submit event on the form id ‘registrationForm’
  • 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 – php-script.php
  • also, serialize the input data using serialize() method
  • define the success to get the success response
  • display the success message in the id ‘msg’
  • After the registered successfully, make empty all the input fields.
$(document).on('submit','#registrationForm',function(e)< e.preventDefault(); $.ajax(< method:"POST", url: "php-script.php", data:$(this).serialize(), success: function(data)< $('#msg').html(data); $('#registrationForm').find('input').val('') >>); >);

6. Write PHP to Insert Registration Data

Now, We have to insert input data into the database, So, create a php-script.php file and write the php code with the MySQL query. The code of this file will run while the ajax code will be executed and sent the post request.

To insert registration data, 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 registerUser() with two parameters $db and $userData.
  4. write a MySQLi query to insert data into the database,
  5. And then call the created function registerUser()
query($query); echo $db->error; if($execute) < echo "You are registered successfully"; >> else < echo "Wrong Confirm password"; >> else < echo "All Fields are required"; >>

7. Test Ajax Registration Form yourself

Now, You can text the ajax registration form by opening it in the web browser.

When you open the registration form will get the First Name, Last Name, gender, Email, Password & Confirm Password input fields.

After that Enter the required details and submit the form. after that, you will be registered successfully without reloading the web page.

Источник

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('Произошла критическая ошибка!'); >, >); >);

Источник

Оцените статью