Google trends Public Holidays Coupon Code Code Compiler

Insert data into mysql table Using Ajax


Dec 25, 2018

Ajax is used to perform actions on the application via the browser and forwarded to the webserver. Usually after clicking the submit button on the form will refresh the browser, AJAX can submit to the webserver without refresh the browser, even ajax can access the database in one event. For more detail

HTML Code:


<html>
 <head>
  <meta http-equiv="Content-Type" c />
 </head>
 <body>
   
   <div>
    <label>Name:</label>
    <input type="text"  name="userName" id="name">
                <label>Email:</label>
    <input type="email"  name="email" id="email">
    <button type="submit" id="submit" name="submit">Submit</button>
   </div>
   
 <body>
</html>

AJAX Code with POST Method:


// Include jQuery plugin
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
$(document).ready(function () {
 $.ajax({
 type: "POST",
 url: "insert.php",
 data: {name: $('#name').val(), email: $('#email').val()},
 cache: true,
 success: function (data) {
  if(data == 'true'){
    alert("Success");
  }else{
    alert("Error");
  }
 }
});
</script>

PHP Code: insert.php


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT into tblTest(name, email)
        values('".$name."', '".$email."')";
 
 mysqli_query($conn, $sql) ;
echo 'true';

Copyright 2024. All rights are reserved