How to insert data in database using jquery Ajax in PHP

To insert data into a database using jQuery Ajax in PHP, you need to perform the following steps:

  • Create a PHP file that will handle the Ajax request and insert the data into the database. This file should contain PHP code to connect to the database and insert the data.
For example, you could create a file named `insert.php` with the following code:

<?php
// Connect to the database
$host = "localhost";
$username = "your-username";
$password = "your-password";
$dbname = "your-dbname";

$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Get the data from the Ajax request
$name = $_POST['name'];
$email = $_POST['email'];

// Insert the data into the database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
  echo "Data inserted successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
  • Create an HTML form that will collect the data to be inserted into the database.
For example, you could create a form like this:

<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name">

  <label for="email">Email:</label>
  <input type="text" name="email" id="email">

  <input type="submit" value="Submit">
</form>
  • Write jQuery Ajax code to submit the form data to the `insert.php` file.
For example, you could write the following jQuery code:

$(document).ready(function() {
  $('#myForm').submit(function(e) {
    e.preventDefault();

    // Get the form data
    var formData = $(this).serialize();

    // Submit the form data via Ajax
    $.ajax({
      url: 'insert.php',
      type: 'POST',
      data: formData,
      success: function(response) {
        alert(response);
      }
    });
  });
});

In this example, the jQuery code listens for the form's `submit` event and uses the `$.ajax()` function to submit the form data via POST to the `insert.php` file. The `success` callback function is called when the Ajax request is successful, and it displays an alert message with the response text.

You can modify this code to fit your specific needs, but the basic structure should remain the same.
Previous Post Next Post