Srikanth Technologies

AJAX with jQuery

In this blog, I implement AJAX using JQuery. JQuery is a JavaScript library developed by John Resig and his company. It greatly simplifies things that you handle with JavaScript.

AJAX is an area where JavaScript is to be used. So, instead of using XMLHttpRequest object and other JavaScript construct to implement AJAX, I will use JQuery to achieve the same, of course with far less code to handle.

In fact, JQuery caught my attention in the recent past as I was referring to some articles and conferences on AJAX etc. Many regarded JQuery as the best JavaScript libraries of all. So tried to know it and  spent some time with it. I found it interesting and here I am sharing my knowledge of JQuery with you.

Here are two simple and quick examples of how to use JQuery to implement AJAX.

Steps to use JQuery

Follow the steps given below to develop a simple AJAX application using JQuery.
  1. First step is to download JQuery from www.jquery.com. You can download either of the versions - Minified, Packed or Uncompressed. Uncompressed is of size 98KB. You know its no big deal at all.

  2. Next, create a web project with your IDE (I use NetBeans 6.1), and place jquery-1.2.6.js in web pages folder in your project window. At the end make sure it is placed in the root directory of your web application. We will refer to it from HTML pages.
  3. Create a simpe JSP (addnumbers.jsp) that takes two numbers and returns sum of the numbers. The code is given below.

    <%
       int n1, n2;
       n1 = Integer.parseInt( request.getParameter("num1"));
       n2 = Integer.parseInt( request.getParameter("num2"));
       out.println(n1 + n2);
    %>
    
  4. Create an HTML page (addnumbers.html) that takes two numbers from user and calls addnumbers.jsp with .get() method of JQuery library.

    <html>
    <script language="javascript" src="jquery-1.2.6.js"></script>      
    <script language="javascript">
    function addNumbers(){
     // use get method to make an AJAX call to addnumbers.jsp
     $.get( "addnumbers.jsp",{num1 : $("#num1").val(), num2 : $("#num2").val()},doUpdate);
    }
    function doUpdate(response)
    {
      if (response) {
          $("#result").val(response);
      }
    }
    </script>
    <body bgcolor="#ffff66">
     <form id="form1" >
      <h2>Using AJAX to Add Numbers with JQUERY</h2>
       <table>
        <tr><td> First Number : </td> <td><input type=text id="num1"></td></tr>
        <tr><td> Second Number :</td><td> <input type=text id="num2" ></td></tr>
        <tr><td> Result:</td><td> <input type=text readonly id="result" ></td></tr>
       </table>
       <br />
       <input type=button ID="Button1" runat="server"  onclick="addNumbers()"  value="Add Numbers" />
      </form>
    </body>
    </html>
    

    The following are important steps in the above program. <

    • Refer to jquery-1.2.6.js using script tag.
    • Use $.get method to make an AJAX call to addnumbers.jsp. No need to use XMLHttpRequest directly. JQuery library takes care of it. The expression $("#num1").val() takes the value from the field that is with id num1. The last parameter to get() method is the callback method.
    • Callback method (doUpdate) has a single parameter that contains the response from the server, which is sum in this case.
    • Check whether response is available and then place it into text field with id result .

  5. If you have implemented AJAX with XMLHttpRequest, you can understand how much of your work is cut short by JQuery.

Using XML with JQuery

The following example shows how to send XML from server and process XML using JQuery. The example takes employee id from user and sends it to JSP on server. Then JSP sends details of employee or error message in the form of XML for JQuery to process on the client.

The following is the code for EMPDETAILS.JSP.

<%@ page import="java.sql.*"  contentType="text/xml"%>
<%
 String empid = request.getParameter("empid");
 // connect to oracle using thin driver
 Class.forName("oracle.jdbc.driver.OracleDriver");
 Connection  con = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");
 Statement st = con.createStatement();
 ResultSet  rs = st.executeQuery("select first_name, salary from employees where employee_id = " + empid);
 if ( rs.next()) { // found
    out.println("<employee><name>");
    out.println(rs.getString(1));
    out.println("</name><salary>");
    out.println( rs.getInt(2));
    out.println("</salary></employee>");
 }
 else {
     out.println("<error>Employee ID Not Found </error>");
 }
 rs.close();
 st.close();
 con.close();
%>

The following is the code for EMPDETAILS.HTML. Apart from taking XML from server and parsing it, it also demonstrates how to show progress icon to user while request is in progress. I have used clock.gif for this. Make sure clock.gif is placed in webpages folder.

Function css is used to add CSS attributes to an element.

<html>
<head>
<title>AJAX and XML with JQUERY </title>
<script language="javascript" src="jquery-1.2.6.js"></script>      
<script language="javascript">
function getEmployeeDetails(){
 // make clock image visible
 $("#clock").css("visibility","visible")
 $.get( "empdetails.jsp",{empid : $("#empid").val()}, displayResult);
}
function displayResult(data) {
  // hide clock image
  $("#clock").css("visibility","hidden") 
  if ( $("error",data).text() != "" )
  {
      // clear fields
      $("#empname").val("")  
      $("#empsal").val("")
      alert( "Error Message :  " + $(data).find("error").text());
  }
  else
  {      
      empname  = $("name",data).text();
      empsal  = $("salary",data).text();
      $("#empname").val( empname );
      $("#empsal").val( empsal )
  }
}
</script>
</head>
<body>
<form id="form1">
    <h2>Employee Details</h2>
    <table>
      <tr>
        <td>Employee ID : </td>
        <td><input type="text" id="empid" size="10"/> <input type="button" value="Get Details" onclick="getEmployeeDetails()" /> </td>
      </tr>
      <tr>
        <td>Employe Name : </td>
        <td><input type="text" id="empname" readonly size="30"/></td>
      </tr>
      <tr>
        <td>Salary :  </td>
        <td><input type="text" id="empsal" readonly size="30"/></td>
      </tr>
    </table>
    <p/>
    <img id="clock" src="clock.gif" style="visibility:hidden" />
    </form>
</body>
</html>

Run EMPDETAILS.HTML page, enter employee id and click on button. After a little while, you must see either details of employee in text fields or error message as alert.

Next we see how to send JSON (JavaScript Object Notation) from JSP and process it using JQuery.

Using JSON qith JQuery

Having seen how to implement AJAX with JQuery and XML with JQuery, let us now see how JQuery is used to process JSON string that comes from server to client.

The following example takes employee id and displays details of employee by getting those details from JSP - empdetails.jsp. For this JSP, we use JDBC to connect to Oracle database. However, you can use any database of your choice in this place.

The following is the code for EMPDETAILS_JSON.JSP, which expects empid and returns details of employee in the form of JSON.

<%@ page import="java.sql.*"  contentType="text/json"%>
<%
 String empid = request.getParameter("empid");
 // connect to oracle using thin driver
 Class.forName("oracle.jdbc.driver.OracleDriver");
 Connection  con = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");
 Statement st = con.createStatement();
 ResultSet  rs = st.executeQuery("select first_name, salary from employees where employee_id = " + empid);
 if (rs.next()) { // if found, send JSON string with employee details to client
    out.println("{\"first_name\":");
    out.println("\"" + rs.getString(1) + "\"");
    out.println(",\"salary\":");
    out.println(rs.getInt(2));
    out.println("}");
 }
 else {  // if not found, send JSON string with error message
     out.println("{\"error\":\"Employee id not found!\"}");
 }
 rs.close();
 st.close();
 con.close();
%>

Let us create HTML page (EMPDETAILS_JSON.HTML) that uses JQuery to make AJAX call to EMPDETAILS_JSON.JSP. We will use getJSON() method to send request to server. The main advantage with this method is, it parses the response string  as JSON. The code is given below. Much of it is easy to understand.

<html>
<head>
<title>AJAX and JSON with JQUERY </title>
<script language="javascript" src="jquery-1.2.6.js"></script>      
<script language="javascript">
 function getEmployeeDetails(){
   $.getJSON( "empdetails_json.jsp",{empid : $("#empid").val()}, displayResult);
 }
 function displayResult(data) {
  if ( data.error) // emp not found
  {
      $("#empname").val("")  // clear fields
      $("#empsal").val("")
      alert( data.error);
  }
  else  // Found employee. Display details
  {      
   $("#empname").val( data.first_name);
   $("#empsal").val( data.salary);
  }
}
</script>
</head>
<body>
<form id="form1">
    <h2>Employee Details</h2>
    <table>
      <tr>
        <td>Employee ID : </td>
        <td><input type="text" id="empid" size="10"/> <input type="button"  value="Get Details" onclick="getEmployeeDetails()" /> </td>
       </tr>
       <tr>
        <td>Employe Name : </td>
        <td><input type="text" id="empname" readonly size="30"/></td>
       </tr>
       <tr>
        <td>Salary :  </td>
        <td><input type="text" id="empsal" readonly size="30"/></td>
       </tr>
    </table>
    </form>
</body>
</html>

Run EMPDETAILS_JSON.HTML page, enter employee id and click on button. After a little while, you must see either details of employee in text fields or error message as alert.

That's all you have to do to use JQuery to implement AJAX, use XML and JSON with JQuery.

For more details regarding JQuery, go to docs.jquery.com. JQuery website itself is providing links to useful resources.