AJAX examples using jQuery for PHP and MySQL

Why do we need to use AJAX? AJAX helps us communicate from the user interface to the server without reloading our page and helps reduce bandwidth costs on the server and improves user experience.

In this tutorial, we will use the JQuery library to implement an AJAX instance for PHP and MySQL, testing the AJAX POST and GET methods with a simple employee save and get records.

So, we will start our code now. Let's create our index.html below.

Index.html file

Here is the complete source code of our index.html:

<!doctype html>
<html lang="en">
<head>
    <title>PHP & MySQL AJAX example Using jQuery</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <!-- Page CSS -->
    <link rel="stylesheet" href="assets/css/styles.css">
</head>

<body>

    <div class="container">

        <br><br>

        <h1>PHP & MySQL AJAX example Using jQuery</h1>

        <br><br>

        <div class="row">
            <div class="col-md-4">
                <h3>Add New Employee</h3>

                <form action="save.php" id="form">
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input class="form-control" type="text" name="email">
                    </div>
                    <div class="form-group">
                        <label for="first_name">First Name</label>
                        <input class="form-control" type="text" name="first_name">
                    </div>
                    <div class="form-group">
                        <label for="last_name">Last Name</label>
                        <input class="form-control" type="text" name="last_name">
                    </div>
                    <div class="form-group">
                        <label for="address">Address</label>
                        <textarea class="form-control" type="text" name="address" rows="3"></textarea>
                    </div>
                    <button type="button" class="btn btn-primary" id="btnSubmit">Submit</button>
                </form>
            </div>

            <div class="col-md-8">
                <h3>List of Employees</h3>
                <div id="employees-list"></div>
            </div>
        </div>
    </div>

    <!-- Must put our javascript files here to fast the page loading -->

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <!-- Page Script -->
    <script src="assets/js/scripts.js"></script>

</body>

</html>

Create database table 

With the above ready, we have to create our database tables. We skip directly to creating the database, just create your database or use our SQL dump on the download file.

CREATE TABLE `employees` (
  `id` int(10) NOT NULL,
  `email` varchar(100) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `address` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `employees`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employees`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;

Save.php 

After creating our form, we will create a save.php file to handle the save functionality with PHP and MySQL after we submit the data from the form via AJAX.

<?php
    $request = $_REQUEST; //a PHP Super Global variable which used to collect data after submitting it from the form
    $email = $request['email']; //get the date of birth from collected data above
    $first_name = $request['first_name']; //get the date of birth from collected data above
    $last_name = $request['last_name'];
    $address = $request['address'];

    $servername = "localhost"; //set the servername
    $username = "root"; //set the server username
    $password = ""; // set the server password (you must put password here if your using live server)
    $dbname = "demos"; // set the table name

    $mysqli = new mysqli($servername, $username, $password, $dbname);

    if ($mysqli->connect_errno) {
      echo "Failed to connect to MySQL: " . $mysqli->connect_error;
      exit();
    }

    // Set the INSERT SQL data
    $sql = "INSERT INTO employees (email, first_name, last_name, address)
    VALUES ('".$email."', '".$first_name."', '".$last_name."', '".$address."')";

    // Process the query so that we will save the date of birth
    if ($mysqli->query($sql)) {
      echo "Employee has been created successfully.";
    } else {
      return "Error: " . $sql . "<br>" . $mysqli->error;
    }

    // Close the connection after using it
    $mysqli->close();
?>

All.php 

In this file, we have created a function that will get all employee records via AJAX and execute every time the employee record is saved and the page is reloaded.

<?php
    $servername = "localhost"; //set the servername
    $username = "root"; //set the server username
    $password = ""; // set the server password (you must put password here if your using live server)
    $dbname = "demos"; // set the table name

    $mysqli = new mysqli($servername, $username, $password, $dbname);

    if ($mysqli->connect_errno) {
      echo "Failed to connect to MySQL: " . $mysqli->connect_error;
      exit();
    }

    // Set the INSERT SQL data
    $sql = "SELECT * FROM employees";

    // Process the query so that we will save the date of birth
    $results = $mysqli->query($sql);

    // Fetch Associative array
    $row = $results->fetch_all(MYSQLI_ASSOC);

    // Free result set
    $results->free_result();

    // Close the connection after using it
    $mysqli->close();

    echo json_encode($row);
?>

Scripts.js 

Then, our last piece of code, we put the ajax functions that save and get employee records here. This code consists of these functions:

all() - Get all employee records via AJAX
submitForm() - Used to store employee records via AJAX
resetForm() - Used to reset the form after successful employee creation

function all() 
{
    // Ajax config
    $.ajax({
        type: "GET", //we are using GET method to get all record from the server
        url: 'all.php', // get the route value
        success: function (response) {//once the request successfully process to the server side it will return result here

            // Parse the json result
            response = JSON.parse(response);

            var html = "";
            // Check if there is available records
            if(response.length) {
                html += '<div class="list-group">';
                // Loop the parsed JSON
                $.each(response, function(key,value) {
                    // Our employee list template
                    html += '<a href="#" class="list-group-item list-group-item-action">';
                    html += "<p>" + value.first_name +' '+ value.last_name + " <span class='list-email'>(" + value.email + ")</span>" + "</p>";
                    html += "<p class='list-address'>" + value.address + "</p>";
                    html += '</a>';
                });
                html += '</div>';
            } else {
                html += '<div class="alert alert-warning">';
                  html += 'No records found!';
                html += '</div>';
            }



            // Insert the HTML Template and display all employee records
            $("#employees-list").html(html);
        }
    });
}

function submitForm() 
{
    $("#btnSubmit").on("click", function() {
        var $this           = $("#btnSubmit"); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#form"; //defined the #form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here
                $this.attr('disabled', false).html($caption);

                // Reload lists of employees
                all();

                // We will display the result using alert
                alert(response);

                // Reset form
                resetForm();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
}

function resetForm() 
{
    $('#form')[0].reset();
}


$(document).ready(function() {

    // Get all employee records
    all();

    // Submit form using AJAX
    submitForm();

});

I hope that in this AJAX example, you will have enough foundation to use jQUERY's AJAX. 

Guess you like

Origin blog.csdn.net/o67f2wpkvdf3bpe8/article/details/130097741