X

Insert Data into MySQL database with PHP and AJAX without refreshing page

http://www.techjunkgigs.com

Hello friends, in this Insert Data into MySQL database with PHP and AJAX without refreshing page tutorial we will use jQuery AJAX method to insert values in our MySQL database without refreshing our web page. So lets begin.

What you need before starting Tutorial?

  • WAMP / XAMPP server (I will be using XAMPP)
  • Notepad++ /Notepad
  • knowledge of PHP, MySQL and JavaScript

Creating Database and Table for Data

I have created a table name users. In users I have three columns (id, username and password). Id is primary key with an auto increment.

Creating HTML Form

<!DOCTYPE html>
<html>
<head>
 <title>PHP MySQL Tutorial|TechJunkGigs</title>
        <script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
 <form action='insertconn.php' method='post' id='insertform' >
 <p>
 <input type='text' name='username' placeholder='user name' id='username' />
 </p>
 <p>
 <input type='text' name='password' placeholder='password' id='password' />
 </p>
 <button id='insert'>Insert</button>
 <p id='result'></p>
 </form>
</body>
</html>

Creating PHP for Data Insert

<?php	
	$con = mysqli_connect("localhost","root","","insertDB");
	$username = $_POST['username'];
	$password = $_POST['password'];
	$query = "insert into users (username, password) values ('$username','$pass')";
	
	if(mysqli_query($con, $sql)){
		echo 'success';
	}
?>

Create File insert.JS

$('#insertform').submit(function(){
	return false;
});
$('#insert').click(function(){
	$.post(		
		$('#insertform').attr('action'),
		$('#insertform :input').serializeArray(),
		function(result){
			$('#result').html(result);
		}
	);
});

Demo

Demo Video

So that’s all for this Insert Data into MySQL database with PHP and AJAX without refreshing page friends. We learned some fundamental things, but you can do whatever you want with the trick. if you found it helpful then, please SHARE. Thank You

[sociallocker]insert[/sociallocker]

Jamaley Hussain: Hello, I am Jamaley. I graduated from Staffordshire University and have always been passionate about Computers, Technology, and Generative AI. Currently, I work as a Senior Data Scientist (AI/ML) and I’m also the founder of TechJunkGigs, a platform dedicated to helping programming students with tutorials on Machine Learning, Data Science, Python, LLM, RAG, Generative AI, and NLP. What started as a blog has now evolved into a valuable resource for students, and I'm committed to sharing knowledge to help them stay updated with industry trends
Related Post