Blog Archive

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.

jQuery AJAX request and response tutorial using Java Servlets
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

<html>
<head>
    <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>

</head>
<body>

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

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

</body>
</html>

Application JavaScript file using jQuery - apps.js

$(document).ready(function() {

    //Stops the submit request
    $("#myAjaxRequestForm").submit(function(e){
           e.preventDefault();
    });
   
    //checks for the button click event
    $("#myButton").click(function(e){
          
            //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
            $.ajax({
                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
                     if(data.success){
                         $("#ajaxResponse").html("");
                         $("#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);
                      $("#ajaxResponse").html(jqXHR.responseText);
                },
               
                //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">
  <display-name>jQuery_Ajax_Request</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description>Get Information about Country - jQuery Ajax Request</description>
    <display-name>CountryInformation</display-name>
    <servlet-name>CountryInformation</servlet-name>
    <servlet-class>com.as400samplecode.CountryInformation</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CountryInformation</servlet-name>
    <url-pattern>/CountryInformation</url-pattern>
  </servlet-mapping>
</web-app>

Application context file for MySQL connection - context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
<Resource auth="Container"
name="jdbc/mysql"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/world"
username="root"
password="mysql"
maxIdle="10"
maxActive="200"
maxWait="5"
removeAbandoned="true"
removeAbandonedTimeout="1200"
/>
</Context>

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() {
        super();
    }

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

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

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

        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        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);
        out.println(myObj.toString());

        out.close();

    }

    //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(); 

            while(rs.next()){ 
                country.setCode(rs.getString("code").trim());
                country.setName(rs.getString("name").trim());
                country.setContinent(rs.getString("continent").trim());
                country.setRegion(rs.getString("region").trim());
                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()));
            }                                                                         

            rs.close();                                                               
            stmt.close();                                                             
            stmt = null;                                                              


            conn.close();                                                             
            conn = null;                                                   

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

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

                stmt = null;                                            
            }                                                        

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

                conn = null;                                            
            }                                                        
        }              

        return country;

    }   

}

Recommended Reading


50 comments :

  1. It is very help full for beginners, Thank you so much for this

    ReplyDelete
  2. Thanks a lot :) nice post. really helpful

    ReplyDelete
  3. thanks good example, but i am not able run the example, after entering country code when i was hit submit button nothing is coming as response, not going to inside the servlet also.

    ReplyDelete
  4. thank u... this this i needed...

    ReplyDelete
  5. Thank you very much.. Keep up the good work..!

    ReplyDelete
  6. thank a lot....i learned new thing .....i will try

    ReplyDelete
  7. Thanks a lot. I have wasted 2-3 days for the same code. finally you have helped me. Thank you very much.

    ReplyDelete
  8. please help us our project is not working maybe it is the problem of database please can you give us source code for this database !!!! please please

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

    $(document).ready(function() {
    $("#cat6Button").click(function(e){ alert( "Handler for .click() called." );
    $.ajax({type: "POST",url: "Information",data: dataString, dataType: "json",
    :
    :
    SCRIPT5009: 'dataString' is undefined
    taskJq.htm, line 19 character 2
    I am getting this error about using jquery ajax method in the above script.

    ReplyDelete
  10. The method add(String, JsonElement) is undefined for the type JSONObject
    PLEASE HELP ME TO RESOLVE THIS ERROR

    ReplyDelete
  11. Hi, is there any book which teaches Ajax, Jquery & uses Servlets to send responses from the server. It'll be of great help if you could suggest me any book which explains in detail. Thanks for the tutorial. It reallly helped.

    ReplyDelete
  12. Thanks a lot.

    ReplyDelete
  13. Thanks awesome

    www.androidspot1995.com

    ReplyDelete
  14. Is not working maybe it is the problem of DB
    please can you give us source code for the database and the configuration?

    ReplyDelete
  15. org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'

    ReplyDelete
  16. could you provide the project in zip

    ReplyDelete
  17. Thank you for the wonderful work. cheers...

    ReplyDelete
  18. Superb man..nicely expalined

    ReplyDelete
  19. Thank you! Helped me a lot. :-)

    ReplyDelete
  20. I stumbled upon this topic via Google. Very interesting view on subject. Thanks for sharing.

    ReplyDelete
  21. good a post
    if i fetch from DB 100 records, and now i want to paginate it
    how i can do it? please help me

    ReplyDelete
  22. You are showing a screenshot of some sort of IDE Could you please tell us which one this is?

    ReplyDelete
  23. It worked, thank you very much..!

    But this article didn't mention following libraries should use to do this;

    - JSON.jar ( http://www.java2s.com/Code/JarDownload/java-json/java-json.jar.zip )
    - GSON.jar ( http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip )

    download above 2 libraries and include them to your JSP project, otherwise it won't work!

    ReplyDelete
  24. It worked, thank you very much..!

    But this article didn't mention following libraries should use to do this;

    - JSON.jar ( http://www.java2s.com/Code/JarDownload/java-json/java-json.jar.zip )
    - GSON.jar ( http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip )

    download above 2 libraries and include them to your JSP project, otherwise it won't work!

    ReplyDelete
  25. đồng tâm
    game mu
    cho thuê nhà trọ
    cho thuê phòng trọ
    nhac san cuc manh
    số điện thoại tư vấn pháp luật miễn phí
    văn phòng luật
    tổng đài tư vấn pháp luật
    dịch vụ thành lập công ty trọn gói
    thương lượng
    thuyết mbp
    erg là gì
    nổi tiếng
    chi square
    nói chuyện trước công chúng
    định lý
    victor vroom
    chiến thắng con quỷ
    điểm cân bằng

    tịch phụ trách mảng này là Vi Biểu đều cảm thấy có thể thả lỏng một chút, nhưng Triệu Quốc Đống kiên quyết không đồng ý.
    - Anh không rõ lợi hại trong đó. Anh nhìn thấy đều là nhà máy chế biến thịt nhỏ, nhưng một khi khu vực trồng cỏ mấy trăm ngàn mẫu được thành lập, đó là một ngành sản xuất khổng lồ. Không chỉ có Đại Hoa và Công ty Tam Điệp, tôi đoán còn có nhiều công ty lớn trong ngành sản xuất này tới đây. Hơn nữa cũng kéo theo mấy công ty liên quan tới.
    Triệu Quốc Đống cũng biết bây giờ còn mơ hồ về quan niệm bảo vệ môi trường, chứ đừng nói là coi trọng.
    - Hai công ty này có chút danh tiếng trong ngành sản xuất, bọn họ khi đầu tư xây dựng nhà máy ở huyện ta đều để đường lui. Nói cách khác lúc nào cũng có thể làm khó chúng ta. Mà quy mô của bọn họ sẽ làm ô nhiễm môi trường. Hoa Lâm có hoàn cảnh tốt đẹp, nếu như nước ô nhiễm bị chảy thẳng ra ngoài sẽ rất nguy hiểm. Nếu như bây giờ không làm cho tốt, ngày sau anh muốn để bọn họ xây dựng thiết bị bảo vệ môi trường càng thêm khó khăn. Nhất là sau khi hiệu quả kinh doanh tốt, mọi người đều chú ý tới hiệu quả, nơi nào còn có thể để ý mấy vấn đề ô nhiễm môi trường đó.
    - Nhưng mà …
    - Anh yên tâm. Hoa Lâm chúng ta có ưu thế, bọn họ đây là muốn ép chúng ta, nhưng chúng ta phải cho bọn họ biết không thể nào làm theo ý mình được. Bọn họ không phải nói tài chính khó khăn sao? Tôi dự định ủng hộ bọn họ trong việc vay vốn của hệ thống ngân hàng.
    Triệu Quốc Đống cười nói.
    - Vay tiền? Nhưng Ngân hàng Công thương và Ngân hàng nông nghiệp đều đã cho bọn họ vay, muốn vay thêm sợ là có chút khó khăn.
    Quế Toàn Hữu cũng hiểu rõ về hai công ty này. Đám này đưa ra yêu cầu rất ngặt nghèo, làm đủ cách gây khó dễ cho chính quyền địa phương. Nếu như không phải trụ sở trồng cỏ của Hoa Lâm đã làm tốt thì sợ hai công ty này chưa chắc đã chọn Hoa Lâm.
    - Ừ, tôi biết, tôi dự định tìm Ngân hàng chính sách nông nghiệp tỉnh.
    Triệu Quốc Đống đã tính toán qua một chút. Hai công ty này đi đầu trong các

    ReplyDelete
  26. Really very neat explanation. could you please tell me the concept of array that how to display all the data fetch from MYSQL regards to corresponding input we are given. for example in our data base we save more than one row with different address in the same code of usa..and when user try to give USA as a code it need to display all the records of row matching to that USA data. thanx for this post

    ReplyDelete
  27. I created the project, but when I click on run on server the server starts then I give the country code, I get this errror :
    java.lang.ClassNotFoundException: CountryInformation
    I don't know why!

    ReplyDelete
  28. 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.html coder

    ReplyDelete
  29. Good Article working fine for me...after wasting time on too many other site,,..finally I go this!

    Many Thanks!

    ReplyDelete
  30. Really a nice explanation and it covers most the new technologies.

    ReplyDelete
  31. I like your point of choice for website yet need to recommend you for sharing. e-commerce designing

    ReplyDelete
  32. This comment has been removed by the author.

    ReplyDelete
  33. Thank you so much. This really helped me a lot, great work!

    ReplyDelete
  34. Never would have thought to use PrintWriter out = response.getWriter(); to return my JSON string to my JQuery get(). Thanks. A really good example for a JSP/servlet guy.

    ReplyDelete
  35. Thank You!! You explained a lot.

    ReplyDelete

  36. Great! Thanks for sharing the information. That is very helpful for increasing my knowledge in this fiel
    Red Ball | | duck life | Slitherio
    Red Ball 2 | Red Ball 3 | Red Ball 4

    ReplyDelete
  37. The share your really gives us excitement. Thanks for your sharing. If you feel tired at work or study try to participate in our games to bring the most exciting feeling. Thank you!
    swords and souls | strike force kitty 2

    ReplyDelete
  38. Very good. you are the winner. Do not forget update new information regularly. thank !
    - slither.io
    - wings.io
    - vanar.io
    - Emoji Facebook
    - diep.io

    ReplyDelete

  39. Thanks for the best blog. it was very useful for me.
    keep sharing such ideas in the future as well. Thanks for giving me the useful information.

    - slither.io
    - wings.io
    - vanar.io
    - Pokemon GO
    - diep.io

    ReplyDelete
  40. Awesome work. It's very helpful.
    Keep it up.
    Thanks.

    ReplyDelete
  41. Cant stop thanking you, its a complete package

    ReplyDelete