0

I send ajax request to servlet and servlet is giving the json object. But in ajax response, i did not receive the josn response . I put alert and log method to check the response comes to success method.But i did not even get the alert / log .

Jsp Ajax request/response:

 $(document).ready(function() {
          $("#searchCntrBtn").click(function(event) {
            event.preventDefault();
            $.ajax({
                type: 'GET',
                dataType: "json",
                url: '/<%=si.webContext%>/servlet/webAdmin.WebAdminGetCntrDetailsServlet',
                success: function(data) 
                {
                    var json = JSON.parse(data);

                    console.log("success", json);
                   // $('#myModal').show();
                   // $('#modalContent').show().html(data);
                }
            });
          })
        })

Servlet :-

response.setContentType("application/json");
          response.setCharacterEncoding("UTF-8");
          PrintWriter out = response.getWriter();
          String jsondata = new Gson().toJson(cntrs);

         // out.write(json);
          response.getWriter().write(jsondata);

          out.print(jsondata);
          System.out.println("JSON data---->"+jsondata);
          out.flush();

Not sure what went wrong here but response is not reaching to the success function in jsp. Can you guys please help me on this . thanks in advance.

RKCY
  • 4,095
  • 14
  • 61
  • 97

2 Answers2

2

use code inside ajax success method

var json = jQuery.parseJSON(data);
console.log("success", json);

and in servlet write code

Gson gson = new Gson();
JsonElement element = gson.toJsonTree(<Object_to_be_passed>);
out.write(element.toString());

and also you have to import two packages com.google.gson.Gson and com.google.gson.JsonElement in servlet

if you pass a model class in json use the variable names to access data in ajax

like if you have a model class Address having fields name and phone you should write code in ajax is json.name & json.phone


Example

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="jquery-3.2.1.js"></script>
        <title>Ajax Sample</title>
    </head>
    <body>
        <div>
            <textarea id="text"></textarea>
            <button onclick="load()">Load Now</button>
        </div>
        <script>
            function load() {
                $.ajax({
                    url: "GetData",
                    type: 'POST',
                    success: function (data, textStatus, jqXHR) {
                        alert(data);
                        var json = jQuery.parseJSON(data);
                        document.getElementById("text").innerHTML = 'Name: ' + json.name + ' & Phone:' + json.phone;
                    }
                });
            }
        </script>
    </body>
</html>

Index.java servlet

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Chirag
 */
public class Index extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(new Address("Chirag", "123456"));
            writer.write(element.toString());
        }
    }

    class Address {

        private final String name;
        private final String phone;

        public Address(String name, String phone) {
            this.name = name;
            this.phone = phone;
        }

        public String getName() {
            return name;
        }

        public String getPhone() {
            return phone;
        }

    }

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

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

    @Override
    public String getServletInfo() {
        return "Get Ajax Result";
    }

}

I used the deployment descriptor to create the servlet address GetData. following the snip part of web.xml

<servlet>
    <servlet-name>Index</servlet-name>
    <servlet-class>Index</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Index</servlet-name>
    <url-pattern>/GetData</url-pattern>
</servlet-mapping>

This code place the value to textarea in html and also make a alert of passed data from servlet to jsp.

Hope it helps..:)

Chirag
  • 555
  • 1
  • 5
  • 20
0

Do check where the problem is occurring. Is the ajax call reaching the servlet? Give a System.out.println statement in the servlet class to check whether its reaching there.

If that's happening and the response is not reaching back, then that means the response is not coming in the right format. Use GSON mentioned in @chirag answer if that's the problem.

Alan Pallath
  • 99
  • 3
  • 14