XMLHttpRequest Ajax in JavaScript

   Using XMLHttpRequest, Ajax Call  to PHP page, MySQL Data in JavaScript

e-trainings-xhr-ajax-db-php-demo

 

What is  XMLHttpRequest?

XMLHttpRequest is a JavaScript's in-built browser object that allows to make HTTP requests to Server.

XMLHttpRequest is used to implement AJAX effect in web application development.

Basically XMLHttpRequest (XHR) objects used to interact with servers. It makes You to retrieve data from a URL without refreshing the complete page. This enables a Web page to update just part of a page without interrupting the user what he is doing on a page.

In this tutorial to implement Ajax feature in web application,   we are using 3 programs.

1. An HTML page allows the user to send a request to the server. 

2. A JavaScript Page, which resides in the middle of the HTML and Server Page, receives the request from the HTML page and sends the request to the server and receives the response and passes it to the HTML page.

3. Server Page here it is a PHP page which will receives the request from JavaScript file communicates with the database to process the request and sends response to client page and updates the content.

  1. php-AjaxDB.html
  2. php-AjaxDB.JS
  3. php-AjaxDB.php



php-AjaxDB.html

This HTML page contains form. When the user selects a value in form, it is sent to the JavaScript function.

In this page, user selects a book. When book selected, a JavaScript method showBook() is invoked. This method sends the selected book ID to the method.

Top↑

<html>
<head>

<title> Coding-zon Demo XMLHttpRequest Ajax in JavaScript PHP</title>
<script type="text/javascript" src="phpAjaxDB.js"></script>
</head>
<body>
<form>
<div id="txtHint"><b>Book info will be listed here.</b></div>
<br />
Select a Book:
<select name = "books" onchange = "showBook(this.value)">
<option value = "001">JavaScript</option>
<option value = "002">jQuery</option>
<option value = "003">PHP</option>
<option value = "004">HTML</option>
<option value = "005">Java</option>
</select>
</form>


</body>
</html> 

 
php-AjaxDB.js

 Top↑

 

This JavaScript file handles the requests which coming from  HTML Page.

Method  showBook() creates  XMLHttpRequest Object. If object not created then shows some warning messages. 

Next It creates a URL string to PHP file with a parameter book_id. Parameter book_id is assigned with a user selected value str.

function showBook(str)
{
xmlhttp=new XMLHttpRequest();
 
 if (xmlhttp==null)
  {
	alert ("Browser does not support HTTP Request");
	return;
  }
 
var url="php-AjaxDB.php?book_id="+str;

xmlhttp.onreadystatechange=stateChanged; 
 
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
 
 }

function stateChanged()
{
	if (xmlhttp.readyState==4)
	{
	document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
	}
}

 

php-AjaxDB.php

PHP file receives the parameters from the url send from js file based on the request it will process the database and send the result as a response to the XMLHttpRequest Object, which automatically updated in a front page.

The PHP file receives book_id as a GET request. Next, it connects to the database and selects the book details based on the given book_id, and prints it in  HTML table format.

TopMenu↑

<?php

$book_id = $_GET["book_id"];
 
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, "booksDB");

if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
 
$sql = "SELECT * FROM books  WHERE book_id = ".$book_id ;

$result = mysqli_query($con, $sql);

echo "<table border='1'>
<tr><th>Book Id</th><th>Title</th><th>Author</th><th>Price</th></tr>";

while($row = mysqli_fetch_assoc($result))
{
 
  echo "<tr>";

  echo "<td>" . $row['book_id'] . "</td>";
  echo "<td>" . $row['title'] . "</td>";
  echo "<td>" . $row['author'] . "</td>";
  echo "<td>" . $row['price'] . "</td>";
 
 echo "</tr>"
 
}
 
echo "</table>";

mysqli_close($con);
 
?>

 Menu↑

 DBQueries

--
-- Database: `booksdb`
--
-- --------------------------------------------------------
--
-- Table structure for table `books`
--

CREATE TABLE IF NOT EXISTS `books` (
  `book_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(30) NOT NULL,
  `author` varchar(30) NOT NULL,
  `price` int(11) NOT NULL,
  PRIMARY KEY (`book_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `books`
--

INSERT INTO `books` (`book_id`, `title`, `author`, `price`) VALUES
(1, 'JavaScript', 'Author1', 200),
(2, 'jQuery', 'Author2', 300),
(3, 'PHP', 'Author3', 260),
(4, 'HTML', 'Author4', 350),
(5, 'Java', 'Author5', 450);

 



With this tutorial, you learned
 

1. How to pass a user selected value to a JavaScript function.
2. How to pass along variables with XMLHttpRequest.
3. Sending query string parameters using XMLHttpRequest to PHP Page
4. Reading query parameter using GET in PHP.
5. Processing request with Database in PHP.
6. Sending response to XMLHttpRequest Object.  

 

 

 Demo:


 

 

 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP