AJAX - Database Connection 
without reloading the page
Ajax is the mastermind to display data directly from database without reloading the page. How to achieve this without calling a Servlets Action or Struts Action without reloading or refreshing the page how to display the data from table. Google showing suggestions without reloading the page.

Here am going to explain how to display data using Database.
Am going to use combination of JavaScript, AJAX and MySql Database.

Steps to connect Database using AJAX

Step 1:
  • Create a Database and Table with fields.
Ex: Database table contains Empid int(20), EmpName varchar(200)

Step 2:
Use a Servlets action or JSP or PHP to write database logic. Am going to use Servlet Action.

Configure Web.xml 
-------------------------
<servlet>
<servlet-name>ajaxtutorial</servlet-name>
<servlet-class>com.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ajaxtutorial</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>

Test.java

public class Test extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
  {
     String val = request.getParameter("id");
     String stor=null;
     Connection con = null;
     PreparedStatement pst =null;
     ResultSet rs=null;
     response.setContentType("text/xml");
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     pst = con.prepareStatement("select Empid, EmpName from employee where Empid=?");
     pst.setString(1,val);
     if(rs.next())
     {
      stor =rs.getString(1);
      response.getWriter().write(stor);
     }
  con.close();
  }catch(SQLException e)
   {
    
   }
}
}

Step 3:
 In your JSP page or PHP page write this JavaScript function

<script type="text/javascript">

function ajaxDB()
{
var boxtype=document.getElementById("boxtype");
var url = "/test?id="+boxtype;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();

}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
var x= document.getElementById("hello");
x.innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
<input type="text" id="boxtype"></input>
<div id="hello"></div>
0 comments