How to Insert Data Using Ajax in PHP

Insert Data Using Ajax in PHP: This tutorial is posted for beginners as well as experienced developers. It will help you insert form data into the MySQL Database without page refresh.

I have shared the best example using ajax, PHP & MySQL. So, You can learn How to Insert Data Using Ajax in PHP and MySQL. All the steps are explained in a simple way. Those are easy to understand. Hence, Continue reading the complete tutorials.

insert data using ajax in php

Insert Data Using Ajax in PHP

I have explained this tutorial in a simple form. Once you learn it, you will insert other form data without reloading the page. This script will work with different types of form data. So, It is very simple to implement in the project.

Read Also –

How to Fetch Data from the database using Ajax

How to update data using Ajax in PHP

Before writing a Script, You must do the following things.

  • Create a project folder. otherwise, you can use the following folder structure for testing purposes.
codingstatus.com/
  |__database.php
  |__ajax-script.js
  |__php-script.php
  |__user-form.php

1. Create MySQL Database

Create MySQL database and table with the following name

  • Database Name- codingstatus ( you can use your own custom database name )
  • Table Name- usertable ( you can use  your own table name)

Table Name – usertable

CREATE TABLE `usertable` (
  `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `fullName` varchar(255) DEFAULT NULL,
  `emailAddress` varchar(255) DEFAULT NULL,
  `city` varchar(255) DEFAULT NULL,
   `country` varchar(50) DEFAULT NULL,
  `created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Connect PHP to MySQL Database

You have to connect PHP to MySQL database with the valid connection credentials –

File Name database.php

<?php

$hostname     = "localhost";
$username     = "root";
$password     = "";
$databasename = "codingstatus.com";
// Create connection
$conn = mysqli_connect($hostname, $username, $password,$databasename);
// Check connection
if (!$connection) {
    die("Unable to Connect database: " . mysqli_connect_error());
}
?>

3. Create an HTML Form

Configure the following point to create an HTML form –

  • Include jquery CDN to execute jquery ajax code.
  • Include external ajax script file  ajax-script.js. This file contains a custom ajax code to insert data without reloading the page. Don’t worry, you will get a complete guide about this file in the next step
  • Create an HTML form with the following form attribute & input fields
    • <form> – This tag must have id="userForm"method="post"
    • Full Name – It should be text input and should have name="fullName" attribute.
    • Email Address – It should be an email input field and should have  name="email" attribute.
    • City – It should be a text input field and should have  name="city" attribute
    • Country – It should be a text input field and should have  name="country" attribute
    • Submit Button – It should be a button.

File Nameuser-form.php

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!--====form section start====-->
<div class="user-detail">
    <h2>Insert User Data</h2>
    <p id="msg"></p>
    <form id="userForm" method="POST">
          <label>Full Name</label>
          <input type="text" placeholder="Enter Full Name" name="fullName" required>
          <label>Email Address</label>
          <input type="email" placeholder="Enter Email Address" name="emailAddress" required>
          <label>City</label>
          <input type="city" placeholder="Enter Full City" name="city" required>
          <label>Country</label>
          <input type="text" placeholder="Enter Full Country" name="country" required>
          <button type="submit">Submit</button>
    </form>
        </div>
</div>
<!--====form section start====-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="ajax-script.js"></script>
</body>
</html>

4. INSERT Data without Reloading Page Using Ajax

You have to configure the following steps to insert data without reloading the page –

  • First of all, apply submit event on the HTML form with id #userForm.
  • Define e.preventDefault() to submit form data without reloading the page.
  • Send POST request to PHP code for inserting data into the database.
  • Declare URL php-script.php. This URL contains PHP code. Don’t worry, It will explain in the next step.
  • Display success or error message  in div with id #msg.

Full Nameajax-script.js

$(document).on('submit','#userForm',function(e){
        e.preventDefault();
       
        $.ajax({
        method:"POST",
        url: "php-script.php",
        data:$(this).serialize(),
        success: function(data){
        $('#msg').html(data);
        $('#userForm').find('input').val('')

    }});
});

5. Insert Data Using PHP

To insert data into the MySQL database, configure the following steps –

  • First, Include database connection file database.php
  • Assign connection variable $conn to a new variable $db
  • Create a custom function insert_data(). This function will insert form data into the database.
  • Then call insert_data()  if all the fields are not empty.
  • Also, Create another custom function legal_input() to convert illegal input to legal input.

File Name – php-script.php

 <?php

include('database.php');
$db=$conn;// database connection  

//legal input values
 $fullName     = legal_input($_POST['fullName']);
 $emailAddress = legal_input($_POST['emailAddress']);
 $city         = legal_input($_POST['city']);
 $country      = legal_input(md5($_POST['country']));
   
if(!empty($fullName) && !empty($emailAddress) && !empty($city) && !empty($country)){
    //  Sql Query to insert user data into database table
    Insert_data($fullName,$emailAddress,$city,$country);
}else{
 echo "All fields are required";
}
 
// convert illegal input value to ligal value formate
function legal_input($value) {
    $value = trim($value);
    $value = stripslashes($value);
    $value = htmlspecialchars($value);
    return $value;
}

// // function to insert user data into database table
 function insert_data($fullName,$emailAddress, $city, $country){
 
     global $db;

      $query="INSERT INTO usertable(fullName,emailAddress,city,country) VALUES('$fullName','$emailAddress','$city','$country')";

     $execute=mysqli_query($db,$query);
     if($execute==true)
     {
       echo "User data was inserted successfully";
     }
     else{
      echo  "Error: " . $sql . "<br>" . mysqli_error($db);
     }
 }

?>

Tutorial Summary

Dear Developers, I hope This tutorial is helpful and you have understood the above concept. Now you can easily implement another Insert data.

If you have any doubts or questions, you can ask me directly through the below comment box. I will definitely reply as soon as possible.

Even you can suggest topics or ideas related to web technology share tutorials. and share this tutorial with your friends who want to learn it.

Thanks for giving the time to this tutorial…