Example of AJAX Database

You can use AJAX to interact with the database present on the server. The following example will demonstrate how a web page can fetch data from the database with the help of AJAX-


      <title>Example of AJAX Database by Tutorialsandyou</title>
      <script type="application/javascript">
         function fetchData(value)
         		var request = new XMLHttpRequest();
			    request.onreadystatechange = function(){
			    if(this.readyState == 4){	       
			       document.getElementById("mobile-info").innerHTML = this.responseText;	       
		        request.open("GET", "/test/mobiles.php?q="+value, true);
      <select id="mydropdown" onchange="fetchData(this.value)">
      	<option value="">Select Mobiles</option>
      	<option value="1">Samsung Galaxy J7</option>
      	<option value="2">Motorola G5</option>
      <div id="mobile-info"></div>

When a user selects any one of the mobiles from the dropdown, an event is fired which is handled by fetchData() function. This function creates an XMLHttpRequest object and sends a request to the server. Once a response is received from the server, it is shown to you by updating HTML and CSS.


   	$conn = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
   	$sql="SELECT name, price, screen_size FROM mobiles WHERE id=".$id;
	if($row){ ?>	 
			<th>Screen Size</th>
			<td><?php echo $row['name']; ?></td>
			<td><?php echo $row['price']; ?></td>
			<td><?php echo $row['screen_size']; ?></td>

This page receives the AJAX request and calls database to get data of selected mobile. Once the data is received from the database, it is placed in the table element and send to the browser.