shyam
shyam

Reputation: 1388

How to fetch data from servlet using ajax?

First of all, this might seem like a duplicate but I assure you I have tried many questions and still hasn't got a proper answer. So I'm asking this here.

I have an HTML form from which I would like to submit a query to a servlet and show the results in a different division.

My HTML code essentially consists of the following:

<form>
    <input name="query" id="query" placeholder="Query">
    <button id="searchDoc">Search</button>
</form>
<div id="search-results"></div>

I have the following jQuery in order to handle the ajax call.

$('#searchDoc').click(function() {
      var q = $('#query').val();
      $.ajax({
         url: "QueryServlet",
         data: {query:q},
         success: function(data) {
             alert("data: " + data);
             $('#search-results').html(data);
         }
      });
  });

My QueryServlet is:

@WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public QueryServlet() {
    super();
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String query = request.getParameter("query");
    QueryUtil qu = new QueryUtil();
    String mySqlQuery = qu.buildMySQLSearchQuery(query);
    System.out.println(mySqlQuery);
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;
    try {
        con = new DbConnection().getConnection();
        st = con.createStatement();
        rs = st.executeQuery(mySqlQuery);
        if(rs != null) {
            response.setStatus(HttpServletResponse.SC_OK);
            while(rs.next()) {
                out.println("<a href=\"DownloadServlet?docId=" + rs.getInt("id") + "\">" + rs.getString("fileName") + "</a>");
            }
        } else {
            // TODO add keywords to database
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

}

Even when I submit a valid query, the div does not get loaded up with the data from the servlet. The data reaches the servlet and gets displayed in the console, but I am unable to retrieve that data from the script.

Upvotes: 1

Views: 4575

Answers (2)

Tiger
Tiger

Reputation: 424

the issue seems related to context path, your path should look like this if servlet is not in context root :-

<host> / <context path>/ <servlet>

Thanks :)

Upvotes: 0

sirnino
sirnino

Reputation: 427

The <button> tag is equivalent to an <input type="submit"/>. If you in your form tag don't declare any action attribute, the standard action causes that the page is reloaded. This causes that, although the returned data are inserted in #search-results div, you'll never be able to see them, because the page is immediately reloaded.

You should deactivate the default "Submit" button this way:

$('#searchDoc').click(function(e) {
      e.preventDefault();
      [....]
  });

This should fix your problem!

Upvotes: 1

Related Questions