How To Update Data From Database Using Ajax In PHP

The finest example using ajax, PHP, and MySQL is what I’ve presented. Therefore, you can learn how to update data using Ajax in PHP and MySQL. Simple explanations are provided for each stage.

  1. Create an HTML form to collect data to be updated.
  2. Write the JavaScript code to send the AJAX request to the PHP script when the form is submitted.
jQuery(document).ready(function() {
  jQuery("#update-form").submit(function(event) {
    event.preventDefault();
    var name = jQuery("#name").val();
    var email = jQuery("#email").val();
    jQuery.ajax({
      url: "update-data.php",
      type: "POST",      
      data: { id: id,
              name : name,
              email : email,
      },
      success: function(response) {
        alert("Data updated successfully!");
      }
    });
  });
});
  1. Create a PHP script to handle the AJAX request and update the data in the database.

File Name: update-data.php

<?php
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "dbname";

  // Connect to database
  $conn = mysqli_connect($servername, $username, $password, $dbname);

  // Check connection
  if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
  }

  // Get form data
  $id = $_POST['id'];
  $name = $_POST['name'];
  $email = $_POST['email'];

  // Update data in database
  $sql = "UPDATE users SET name='$name', email='$email' WHERE id=$id";
  if (mysqli_query($conn, $sql)) {
    echo "Record updated successfully";
  } else {
    echo "Error updating record: " . mysqli_error($conn);
  }

  mysqli_close($conn);
?>

Submit a Comment

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

Subscribe

Select Categories