Finding a simple tutorial to submit a form without refreshing the page is almost impossible to find. Many of the tutorials don’t work because they left out steps and some of them are unnecessarily long. After hours of Google searching; here is my simple, to the point tutorial for submitting a html form without refreshing the page using AJAX. NOTE: Some prior knowledge of SQL/MySQLi & PHP expected (that is how you save your information in the database). 

<form id=”form” name=”form”>
<input type=”text” name=”sessionid” id=”sessionid”/>
<label>product id</label>
<input type=”text” name=”productid” id=”productid” />
<input type=”text” name=”quantity” id=”quantity”/>
<input type=”submit” name=”submit” value=”Submit Form” />
<script src=” “></script>

<script type=”text/javascript”>
alert(“Added to Cart”);
//Get the Variables
let sessionid = $(‘#sessionid’).val();
let productid = $(‘#productid’).val();
let quantity = $(‘#quantity’).val();
//Ajax post
url: ‘save-to-cart.php’,
type: ‘post’,
data: {sessionid:sessionid, productid:productid, quantity:quantity},
dataType: ‘json’,
THE PHP (MySQLi Example)
* Created by PhpStorm.
* User: staceygardner
* Date: 7/30/20
* Time: 11:47 AM
/// Replace the variables with your information
$servername = “localhost”;
$username = “your_username”;
$password = “your_password”;

$dbname = “your_database_name”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);

$productid = $_POST[‘productid’];
$sessionid = $_POST[‘session’];
$quantity = $_POST[‘quantity’];

$sql = “INSERT INTO cart (product_id, sessionid, quantity) VALUES (‘”.$productid.“‘, ‘”.$sessionid.“‘, ‘”.$quantity.“‘)”;

if (mysqli_query($conn, $sql)) {
echo “New record created successfully”;
$response = “good”;
} else {
echo “Error: ” . $sql . “” . mysqli_error($conn);
} ?>
Submitting a Simple HTML Form Without Refreshing the Page – AJAX

Leave a Reply

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