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 –

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 –

Читайте также:  Php ждать выполнения скрипта

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.

Источник

Ajax form submission with PHP.

This is a basic tutorial on how to create an Ajax form that submits POST data to a PHP script. For this example, we will setup two files:

  1. The web page that displays our form.
  2. The PHP script that receives our form data via Ajax.

Note: If you are completely new to the concept of Ajax requests, then you should probably check out my tutorial on Ajax requests with JQuery, as it provides a basic introduction to the topic.

Our example web page, which contains the form and Ajax submission script:

       
Your Email Address:

An explanation of the code above:

  1. We created a basic HTML form that allows users to submit their email address. Note that we gave our form element the ID “my_form_id” and that we gave our text field the ID “email”. When you are using JavaScript and JQuery, it is extremely beneficial to give your HTML elements a unique ID, simply because it makes it easier to access them.
  2. We included the JQuery library from the JQuery CDN.
  3. In our custom JavaScript, we place our code inside the document ready function, simply because we do not want our JS to be executed until the page has been properly loaded.
  4. We attach an event handler onto our form element. This event handler will be called whenever the user attempts to submit the form (when they hit enter or click on the submit button). Note how we referenced our form by its ID, which is “my_form_id”.
  5. Once the user has attempted to submit the form, we prevent the default event / behavior from taking place. Remember that the default behavior of a web form is to direct itself to the action URL. When the action URL is not specified (like in our example), it will attempt to submit itself to the current page. We do not want to this happen, as it will reload the page and prevent our Ajax request from being executed.
  6. We grab the value that the user has entered into the email text field (we reference this text field by its ID).
  7. We execute a POST Ajax request to our submission script, which is aptly-named submission.php

If you run the example above, you’ll see that the form is submitted via Ajax and that our JavaScript alerts the output that it received from our PHP script.

Our PHP file.

Our PHP file (we called it submission.php) that processes the form data is pretty straight forward:

 echo 'Received email was: ' . $emailAddress;

Basically, it takes in the POST value that we submitted via Ajax before printing it out. Our Ajax script will receive this output as soon as the request has been completed.

Obviously, your PHP script will probably be a little more complex, as it could be sending an email or inserting data into a database.

Hopefully, this tutorial has pointed you in the right direction!

Источник

How to Submit Form using Ajax in PHP?

In this post, we will learn How to Make a Form Submit in ajax PHP. i explained simply step by step How To Use Form Submit using Ajax in PHP & MySQL. Here you will learn how to Form submit to database Using ajax. This tutorial will give you simple example of ajax form submit php mysql Code Example.

I will give you simple Example of How to make a ajax form submit in PHP.

So let’s see bellow example:

Form Submit using Ajax in PHP MySQL Example

Name

Email address







И второй файл, в котором будет находиться серверная логика, написанная на php:

"; $message .= "E-mail пользователя: " . $_POST['user_email'] . "
"; $message .= "Текст письма: " . $_POST['text_comment']; send_mail($message); // отправим письмо // выведем сообщение об успехе $msg_box = "Сообщение успешно отправлено!"; >else< // если были ошибки, то выводим их $msg_box = ""; foreach($errors as $one_error)< $msg_box .= "$one_error
"; > > // делаем ответ на клиентскую часть в формате JSON echo json_encode(array( 'result' => $msg_box )); // функция отправки письма function send_mail($message)< // почта, на которую придет письмо $mail_to = "my@mail.ru"; // тема письма $subject = "Письмо с обратной связи"; // заголовок письма $headers= "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=utf-8\r\n"; // кодировка письма $headers .= "From: Тестовое письмо \r\n"; // от кого письмо // отправляем письмо mail($mail_to, $subject, $message, $headers); > ?>

Исходные коды подробно прокомментированы, поэтому что либо еще тут писать смысла нет. Остается только выложить исходники — вот они.

Источник

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