PHP Ajax Update Data in MySQL By Using jQuery in Bootstrap Modal

In this post we will discuss how we can update data in MySQL data from tables using Bootstrap Modal using PHP scripts with Ajax queries without refreshing the page. In the previous three tutorial, we show how to insert,delete, and display data into a MySQL table using PHP scripts with Ajax jQuery.

Now I am explain how to update a record or data with out refreshing page using AJAX-jQuery and PHP MYSQL.
Updating a data or record using AJAX-Jquery is a very simple process.As we are going to discuss that we need database from where we update a record without refreshing a page. Let us see database details for it.

So let’s get started, but before you read the last post, you can read it here.

See also

Creating MYSQL Connection in PHP

For importing and exporting database in MySql will make a separate file ‘database.php’. Add the following code and replace the database credentials with yours. You can find your db credentials in Application Access details:

database.php

<?php  
      // create database connectivity  
      $servername = "localhost";  
      $username = "root";  
      $password = "";  
      $database = "testing";  
      // Create connection  
      $con = new mysqli($servername, $username, $password, $database);  
      // Check connection  
      if ($con->connect_error) {  
            die("Connection failed: " . $con->connect_error);  
      }  
 ?>  

Creating HTML Page

  1. Now we will create a simple index page to show users table records after inserting in users table by fetching value from database.
  2. You can use the following HTML code to create your page. Copy and save it as index.php in your project folder.

index.php

<!DOCTYPE html>  
 <html lang="en">  
 <head>  
  <title>CRUD Application in PHP Mysqli using jQuery AJAX</title>  
  <meta charset="utf-8">  
  <meta name="viewport" content="width=device-width, initial-scale=1">  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>  
 </head>  
 <body>  
 <div class="container">  
  <h2 style="text-align: center;">CRUD Application in PHP Mysqli using jQuery AJAX</h2>  
       <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">  
            <div class="modal-dialog" role="document">  
              <div class="modal-content">  
                  <div class="modal-header">  
                     <h2 class="modal-title" id="exampleModalLabel"><b>Edit User Record</b></h2>  
                     <button type="button" class="close" data-dismiss="modal" aria-label="Close">  
                      <span aria-hidden="true">×</span>  
                     </button>  
                  </div>  
                  <div id="editForm">   
                  </div>  
              </div>  
          </div>  
       </div>   
    </div>  
 </body>  
 </html>  
 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>  
 <script type="text/javascript">  
      $(document).ready(function(){  
           // Edit record to mysqli from php using jquery ajax  
           $(document).on("click",".edit-btn",function(){  
                var id = $(this).data('id');  
                $.ajax({  
                     url :"fetch.php",  
                     type:"POST",  
                     cache:false,  
                     data:{editId:id},  
                     success:function(data){  
                          $("#editForm").html(data);  
                     },  
                });  
           });  
           // User record update to mysqli from php using jquery ajax  
           $(document).on("click","#editSubmit", function(){  
                var edit_id = $("#editId").val();  
                var name = $("#editName").val();  
                var email = $("#editEmail").val();  
                var password = $("#editPassword").val();  
                $.ajax({  
                     url:"update.php",  
                     type:"POST",  
                     cache:false,  
                     data:{edit_id:edit_id,name:name,email:email,password:password},  
                     success:function(data){  
                          if (data ==1) {  
                               alert("User record updated successfully");  
                               loadTableData();  
                          }else{  
                               alert("Some thing went wrong");       
                          }  
                     }  
                });  
           });  
      });  
 </script>  

fetch.php

<?php  
      // create database connectivity  
      require_once('database.php');  
      if (isset($_POST['editId'])) {  
           $editId = $_POST['editId'];  
      }  
      // fetch data from student table..  
      $sql = "SELECT * FROM users WHERE id = {$editId}";  
      $query = $con->query($sql);  
      if ($query->num_rows > 0) {  
      $output = "";  
      while ($row = $query->fetch_assoc()) {  
      $output .= "<form>  
            <div class='modal-body'>  
                 <input type='hidden' class='form-control' id='editId' value='{$row['id']}'>  
             <div class='form-group'>  
               <input type='text' class='form-control' id='editName' value='{$row['name']}'>  
             </div>  
             <div class='form-group'>  
               <input type='text' class='form-control' id='editEmail' value='{$row['email']}'>  
             </div>  
             <div class='form-group'>  
               <input type='text' class='form-control' id='editPassword' value='{$row['password']}'>  
             </div>  
            </div>  
            <div class='modal-footer'>  
             <button type='button' class='btn btn-secondary' data-dismiss='modal'>Close</button>  
             <button type='button' class='btn btn-info' id='editSubmit'>Save changes</button>  
            </div>  
          </form>";            
        }  
      }  
      echo $output;  
 ?>

update.php

<?php  
      include "database.php";  
      // insert data student table  
      $id = $_POST['edit_id'];  
      $name = $_POST['name'];  
      $password = md5($_POST['password']);  
      $email = $_POST['email'];  
      $query = "UPDATE users SET name='{$name}',email='{$email}', password='{$password}' WHERE id='{$id}'";  
      if ($con->query($query)) {  
           echo 1;  
      }else{  
           echo 0;  
      }  
 ?>  

Conclusion

This post is about how to use AJAX to update data from a database in PHP. If you have any confusion in my code or a problem with the steps, don’t worry ask in your comments. thank you.

You can always support by sharing on social media or recommending my blog to your friends and colleagues.    

If you have any suggestions or problems about this tutorial, please comment on the  form below😊

PHP Ajax Update Data in MySQL By Using jQuery in Bootstrap Modal

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *