jQuery

Get data from a database without refreshing the browser using Ajax

In this tutorial, we are going to see how to get data from a database without refreshing the browser using Ajax.
 

Step 1: Create an HTML form to load the data

First we will create a simple form to get user information. Create a page called “index.html” and paste the code below into it.

<html>
	<head>
	    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
	<script type="text/javascript">
		//Put the JQuery code here
	</script>
	</head>
	<body>
		<input type="text" name="name" id="name" onkeyup="getdata();">
		<div id="res">  </div>
	</body>
</html>

When the user types thier name on the input, and clicks the Enter key, the onkeyup event occurs by calling the getdata() method.
 

 

Step 2: Get data with Ajax / jQuery

We will use the AJAX method to retrieve the data without refreshing the page.

function getdata()
{
	 var name = document.getElementById("name");
		
	 if(name)
	 {
		$.ajax({
			type: 'post',
			url: 'getdata.php',
			data: {
			   name:name,
			},
			success: function (response) {
			   $('#res').html(response);
			}
		});
	 }
	 else
	 {
		$('#res').html("Enter user name");
	 }
}

 

Step 3: Connect to the database and recover the data

In this step, we query the database and get the desired results.

// getdata.php file

<?php
	if( isset( $_POST['name'] ) )
	{
		$name = $_POST['name'];

		mysql_connect('localhost', 'root', ' ');

		mysql_select_db('user');

		$data = " SELECT age FROM user WHERE name LIKE '$name%' ";

		$query = mysql_query($data);

		while($row = mysql_fetch_array($query))
		{
		   echo "<p>".$row['age']."</p>";
		}
	}
?>

In this tutorial, we saw how to get data from a database without refreshing the browser. You can further customize this code according to your needs.
 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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