PHP, AJAX and JavaScript POST Requests in MYSQL Database

If you want to create a post request with PHP and JavaScript using AJAX, you can use the code below. You need to create two files. The first file is called demo.php in it we will put the HTML form and the JavaScript code. The second file is demo1.php which contains only PHP code. This is the easiest way to create a post request. The example is maximally simplified to make the code legible and easy to use. Keep in mind that all fields must be protected and secure, for this an additional function must be used that will protect your database. Example:

mysqli_real_escape_string($conn, $_POST['field_name']); // Be sure to do this because it's important! 

This is the content of the first file demo.php

<form>
	<label for="firstname">Name: </label>
	<input type="text" id="firstname" name="firstname" value="<?php isset($_POST['firstname']); ?>">
	<label for="email">Email: </label>
	<input type="email" id="email" name="email" value="<?php isset($_POST['email']); ?>">
	<button type="button" onclick="saveToDB()">Save</button>
</form>
<script>
	function saveToDB() {
		event.preventDefault(); // Prevent form from submitting in the traditional way
		let xhr = new XMLHttpRequest(); // Create a new XMLHttpRequest object
		let email = document.getElementById("email").value; 
		let firstname = document.getElementById("firstname").value; 
		xhr.open("POST", "demo1.php", true); // Open a POST request to the PHP script
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // Set the content type
		xhr.send("firstname="+firstname+"&email="+email);
	}
</script>

This is the content of the second file demo1.php which contains only PHP code and which will be called via AJAX without reloading the page again.

	// Database connection
	$servername = "localhost";
	$username = "admin";
	$password = "12345678";
	$dbname = "my_dbname";
	$conn = new mysqli($servername, $username, $password, $dbname);
	
	// Form fields
	$name = $_POST['firstname'];
	$email = $_POST['email'];
	$password = "1111111";
	$ip = "11.22.33.44";
	
	// Insert data into database
	$sql = 'INSERT INTO users (firstname, password, email, ip) VALUES ("'.$name.'", "'.$password.'", "'.$email.'", "'.$ip.'")';
	mysqli_query($conn, $sql);

	// Close database connection
	$conn->close();

Leave a Reply