A Simple AJAX with JAVA Example
A Simple AJAX with JSP example
Java Tutorial Home
What is Ajax?
AJAX stands for Asynchronous JavaScript And XML, Ajax is a technique allows communicating with servers asynchronously. It means at the same time, the server can receive the request and send the response to the client. Ajax implemented with the help of XMLHttpRequest Object. It is a predefined object supported by every browser. Supports different types of data formats such as XML, HTML, JSON and text files.
In this tutorial, we are going to learn how to make an AJAX call using JavaScript XMLHttpRequest Object using JSP and MySQL.
Table of Contents
Project Structure:
Create a web project in eclipse create the following files which are marked in a picture and copy the code given below in those files. And create a table in the database and insert the data using queries below. And run the jspAjaxDB.html file in browser. If everything is fine, you will see the Result given below, result-image.
jspAjaxDB.html
<html> <head> <title> Coding-zon Demo-A Simple Ajax Call in Java & MySQL</title> <script type="text/javascript" src="js/jspAjaxDB.js"></script> </head> <body> <form> <h2> Ajax Call with JavaScript XMLHttpRequest in Java & MySQL </h2> <b>Car Info will be listed here.</b> <div id="txtHint"></div> <br /> Select a Book: <select name = "cars" onchange = "showCar(this.value)"> <option value = "1">Mercedes Benz</option> <option value = "2">Range Rover</option> <option value = "3">Harrier</option> <option value = "4">LandCruiser </option> <option value = "5">Security Vehicles</option> <option value = "6">Wedding Limousine</option> </select> </form> </body> </html>
jspAjaxDB.js
function showCar(str) { xmlhttp = new XMLHttpRequest(); // creating new XMLHttpRequest object if (xmlhttp==null) { alert ("Browser does not support HTTP Request"); return; } //creating URL to JSP to retrieve data from backend. var url="jspAjaxDB.jsp?car_id="+str; xmlhttp.onreadystatechange = stateChanged; xmlhttp.open("GET",url,true); // asynchronus is true xmlhttp.send(null); } function stateChanged() { if (xmlhttp.readyState == 4) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } }
/* 0 = NUNSENT(A request that has not called opend() yet) 1 = OPENED (Opend but not sent) 2 = HEADERS_RECEIVED(Headers and status received) 3 =Loading(Downloading responseText) 4 =DONE (Data transmission complete) */
jspAjaxDB.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h2> <%@ page import="java.sql.*" %> <% int car_id = Integer.parseInt(request.getParameter("car_id")); Connection con; try{ Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/cars","root",""); PreparedStatement ps=con.prepareStatement("select * from tbl_cars where car_id = ?"); ps.setInt(1,car_id); ResultSet rs=ps.executeQuery(); out.println("<table border='1' width='50%'> "); out.println("<thead><tr><td>Car Id</td><td>CarName</td><td>Car Type</td><td>Price</td> </tr></thead>"); while(rs.next()){ out.print("<tr><td>" + rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td><td>"+rs.getString(3)+"</td><td>"+rs.getInt(4)+"</td></tr>"); } out.println("</table>"); con.close(); }catch(Exception e){e.printStackTrace();} %> </h2> </body> </html>
Queries:
--
-- Database: `cars` -- -- -------------------------------------------------------- -- -- Table structure for table `cars` -- CREATE TABLE IF NOT EXISTS `cars` ( `car_id` int(11) NOT NULL AUTO_INCREMENT, `car_name` varchar(255) NOT NULL, `car_type` varchar(255) NOT NULL, `price` int(11) NOT NULL, `capacity` int(11) NOT NULL, PRIMARY KEY (`car_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ; -- -- Dumping data for table `cars` -- INSERT INTO `cars` (`car_id`, `car_name`, `car_type`, `price`, `capacity`) VALUES (1, 'Mercedes Benz', 'Mercedes Benz', 22000 , 5, ), (2, 'Range Rover', 'LandRover', 18000 , 6), (3, 'Harrier', 'Toyota', 19000, 6), (4, 'LandCruiser V8', 'LandCruiser ', 18000, 5), (5, 'Security Vehicles', 'Hammar Cars' 2000, 8), (6, 'Wedding Limousine', 'Wedding Limousine', 21000, 10 );
Result:
Comments
Post a Comment