How To Insert Data Using Ajax In PHP

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

  1. Create an HTML form with input fields for the data you want to insert.
  2. Add a JavaScript function to handle the form submission. This function should use jQuery’s $.ajax method to send a POST request to the server, containing the data to be inserted.
  3. On the server side, create a PHP script that listens for the POST request. This script should extract the data from the request and use it to insert a new record into the MySQL database.
  4. Once the insert is complete, have the server send a response back to the client to indicate that the insert was successful.
  5. In the JavaScript function, handle the response by displaying a message to the user or redirecting them to another page.
  1. Create a HTML form to collect user input
<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email">
  <input type="button" value="Submit" onclick="submitForm()">
</form>

2. Create a JavaScript function to handle the form submission

<script>
  function submitForm() {
    var name = jQuery("#name").val();
    var email = jQuery("#email").val();
    var dataString = "name=" + name + "&email=" + email;

    // AJAX code to submit form.
    jQuery.ajax({
      type: "POST",
      url: "insert.php",
      data: dataString,
      cache: false,
      success: function(result){
        alert(result);
      }
    });
  }
</script>

3. Create a PHP script to handle the AJAX request and insert the data into the database

File name: insert.php

<?php
  if(isset($_POST["name"]) && isset($_POST["email"])) {
    // Get the data
    $name = $_POST["name"];
    $email = $_POST["email"];
  
    // Connect to the database
    $conn = mysqli_connect("hostname", "username", "password", "dbname");
  
    // Insert the data into the database
    $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
    if (mysqli_query($conn, $sql)) {
      echo "Data inserted successfully!";
    } else {
      echo "Error: " . $sql . " " . mysqli_error($conn);
    }
  
    // Close the connection
    mysqli_close($conn);
  }
?>


Submit a Comment

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

Subscribe

Select Categories