jQuery AJAX request and response example - Java Servlets, MySQL and JSON

Why not make AJAX request using plain JavaScript. Well guess what it's not programmer friendly, that's where all these JavaScript frameworks such as jQuery, ExtJs, Dojo etc. are good at. They encapsulate a lot of the underlying technology and provide us programmers with clean API's that has lot of config options and event triggers to handle anything from a simple form submit to something more complicated.

The method for AJAX request is jQuery.ajax( url [, settings] )

The $.ajax() method returns the jqXHR object. URL is a string containing the URL to which the request is sent and settings are a set of key/value pairs that configure the Ajax request. All settings are optional.

In this tutorial we are going to cover the following topics ...
  • Capture form data and send that to the Server using AJAX request
  • Intercept the request before it was sent and add some extra parameters
  • Check if our request to server was successful or not
  • Display the JSON response from the Server
  • Setup connection to MySQL from Tomcat Server
  • Create Java Servlets to process our AJAX request and access MySQL database

jQuery AJAX request and response tutorial using Java Servlets
jQuery AJAX request and response tutorial using Java Servlets
jQuery AJAX request and response tutorial using Java Servlets
We have created a form that takes a country code and then makes an AJAX request to get more information about the country if the country code is valid. Also we intercept the request using beforeSend config to add some dummy data to the request and disable the SUBMIT button until we receive a response from the server. After we receive the response we display the results inside the ajaxResponse DIV tag.

Application HTML file - index.html

    <title>jQuery Ajax POST data Request and Response Example</title>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="app.js"></script>


    <form id="myAjaxRequestForm">
            <legend>jQuery Ajax Form data Submit Request</legend>

                    <label for="countryCode">Country Code:</label><br />
                    <input id="countryCode" type="text" name="countryCode" />
                    <input id="myButton" type="button" value="Submit" />
    <div id="anotherSection">
            <legend>Response from jQuery Ajax Request</legend>
                 <div id="ajaxResponse"></div>


Application JavaScript file using jQuery - apps.js

$(document).ready(function() {

    //Stops the submit request
    //checks for the button click event
            //get the form data and then serialize that
            dataString = $("#myAjaxRequestForm").serialize();
            //get the form data using another method 
            var countryCode = $("input#countryCode").val(); 
            dataString = "countryCode=" + countryCode;
            //make the AJAX request, dataType is set to json
            //meaning we are expecting JSON data in response from the server
                type: "POST",
                url: "CountryInformation",
                data: dataString,
                dataType: "json",
                //if received a response from the server
                success: function( data, textStatus, jqXHR) {
                    //our country code was correct so we have some information to display
                         $("#ajaxResponse").append("<b>Country Code:</b> " + data.countryInfo.code + "<br/>");
                         $("#ajaxResponse").append("<b>Country Name:</b> " + data.countryInfo.name + "<br/>");
                         $("#ajaxResponse").append("<b>Continent:</b> " + data.countryInfo.continent + "<br/>");
                         $("#ajaxResponse").append("<b>Region:</b> " + data.countryInfo.region + "<br/>");
                         $("#ajaxResponse").append("<b>Life Expectancy:</b> " + data.countryInfo.lifeExpectancy + "<br/>");
                         $("#ajaxResponse").append("<b>GNP:</b> " + data.countryInfo.gnp + "<br/>");
                     //display error message
                     else {
                         $("#ajaxResponse").html("<div><b>Country code in Invalid!</b></div>");
                //If there was no resonse from the server
                error: function(jqXHR, textStatus, errorThrown){
                     console.log("Something really bad happened " + textStatus);
                //capture the request before it was sent to server
                beforeSend: function(jqXHR, settings){
                    //adding some Dummy data to the request
                    settings.data += "&dummyData=whatever";
                    //disable the button until we get the response
                    $('#myButton').attr("disabled", true);
                //this is called after the response or error functions are finsihed
                //so that we can take some action
                complete: function(jqXHR, textStatus){
                    //enable the button 
                    $('#myButton').attr("disabled", false);


jQuery AJAX request and response tutorial using Java Servlets

Application config file - web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <description>Get Information about Country - jQuery Ajax Request</description>

Application context file for MySQL connection - context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
<Resource auth="Container"

Java bean containing Country Information - Country.java

package com.as400samplecode;

public class Country {
    String code = null;
    String name = null;
    String continent = null;
    String region = null;
    Double lifeExpectancy = null;
    Double gnp = null;
    public String getCode() {
        return code;
    public void setCode(String code) {
        this.code = code;
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;
    public String getContinent() {
        return continent;
    public void setContinent(String continent) {
        this.continent = continent;
    public String getRegion() {
        return region;
    public void setRegion(String region) {
        this.region = region;
    public Double getLifeExpectancy() {
        return lifeExpectancy;
    public void setLifeExpectancy(Double lifeExpectancy) {
        this.lifeExpectancy = lifeExpectancy;
    public Double getGnp() {
        return gnp;
    public void setGnp(Double gnp) {
        this.gnp = gnp;


Java Servlet processing jQuery AJAX request - CountryInformation.java

package com.as400samplecode;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class CountryInformation extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public CountryInformation() {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String countryCode = request.getParameter("countryCode");

        PrintWriter out = response.getWriter();
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400");

        Gson gson = new Gson(); 
        JsonObject myObj = new JsonObject();

        Country countryInfo = getInfo(countryCode);
        JsonElement countryObj = gson.toJsonTree(countryInfo);
        if(countryInfo.getName() == null){
            myObj.addProperty("success", false);
        else {
            myObj.addProperty("success", true);
        myObj.add("countryInfo", countryObj);



    //Get Country Information
    private Country getInfo(String countryCode) {

        Country country = new Country();
        Connection conn = null;            
        PreparedStatement stmt = null;     
        String sql = null;

        try {      
            Context ctx = (Context) new InitialContext().lookup("java:comp/env");
            conn = ((DataSource) ctx.lookup("jdbc/mysql")).getConnection(); 

            sql = "Select * from COUNTRY where code = ?"; 
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, countryCode.trim());
            ResultSet rs = stmt.executeQuery(); 

                country.setLifeExpectancy(rs.getString("lifeExpectancy") == null ? new Double(0) : Double.parseDouble(rs.getString("lifeExpectancy").trim()));
                country.setGnp(rs.getString("gnp") == null ? new Double(0)  : Double.parseDouble(rs.getString("gnp").trim()));

            stmt = null;                                                              

            conn = null;                                                   

        catch(Exception e){System.out.println(e);}                      

        finally {                                                       
            if (stmt != null) {                                            
                try {                                                         
                } catch (SQLException sqlex) {                                
                    // ignore -- as we can't do anything about it here           

                stmt = null;                                            

            if (conn != null) {                                      
                try {                                                   
                } catch (SQLException sqlex) {                          
                    // ignore -- as we can't do anything about it here     

                conn = null;                                            

        return country;



Recommended Reading

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.