AJAX HTML Javascript jQuery PHP Example MORE
Need a Website Or Web Application Or Any Help.Contact Us: +91 9437911966 (Whatsapp) Note: Paid Service

How to Insert Data using serialize method PHP Ajax


Here we using 3 file for Insert data using jquery serialize method Ajax.

  1. database.php
  2. index.php
  3. save.php

Table user_data

   CREATE TABLE `user_data` (
  `id` int(11) NOT NULL,
  `FirstName` varchar(100) NOT NULL,
  `LastName` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

database.php

<?php
	$servername = "localhost";
	$username = "root";
	$password = "";
	$db="school";
	$conn = mysqli_connect($servername, $username, $password,$db);
?>

index.php

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).on('click','#save',function(e) {
    var data = $("#form-search").serialize();
    $.ajax({
         data: data,
         type: "post",
         url: "save.php",
         success: function(data){
              alert(data);
         }
	});
});
</script>
</head>
<body>
	<form action="" id="form-search">
	  First name: <input type="text" name="FirstName" value="Mickey"><br>
	  Last name: <input type="text" name="LastName" value="Mouse"><br>
	</form>
	<button id="save" name="save">Serialize form values</button>
</body>
</html>
  

save.php

<?php
	include 'database.php';
$FirstName=$_POST['FirstName'];
$LastName=$_POST['LastName'];
if(isset($_POST['save'])){
	$sql = "INSERT INTO `crud`( `FirstName`, `LastName`) 
	VALUES ('$FirstName','$LastName')";
	if (mysqli_query($conn, $sql)) {
		echo "Succeess !";
	} 
	else {
	    echo "Error !";
	}
	mysqli_close($conn);
}
?>