0

I am trying my first web application where I am trying to use Ajax call to get and retrieve json data from server, but for some reason I am not able to see the json response after the ajax call.

I read few posts on this, but with no luck, can someone pls help me here...

<form method="post">
    <input id="show" type="submit" value="submit" />
</form>
<div id="displayNewsDiv"></div>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#show").click(function() {
            alert("h");
            $.ajax({
                url: "News",
                type: "Post",
                data: {"results":true},
                dataType: "json",
                success: function(data) {
                    debugger
                    alert(data);
                }
            })
            /* $.post("News", {"results": true}, function(data) {
                debugger
                alert(data);
                console.log("done")
                console.log(data)
            }) */
        })
    })
</script>

News.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    List<String> newsList = new ArrayList<String>();

    Path path = Paths.get(request.getServletContext().getRealPath("helpTextFile.txt"));
    try {
        newsList = Files.readAllLines(path);
        PrintWriter writer = response.getWriter();
        //writer.println(writer);
        String json = new Gson().toJson(newsList);
        response.setContentType("application/json");
        //new Gson().toJson(newsList, writer);
        writer.write(json);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

File data:

new_12314124124:2018.06.09:2:News 1
new_12314124124:2018.03.03:1:News 2
new_12314124124:2018.04.07:3:News 3

I ran on debug mode, and I can see the data getting populated in the list and it converts to json without error, but still I am not able to see the data nor my debugger in ajax ever runs.

cFrags
  • 11
  • 5
  • I know how to return, but its not working in my case....Can you please re open it – cFrags Jun 09 '18 at 12:25
  • Possible duplicate of [jQuery ajax request with json response, how to?](https://stackoverflow.com/questions/9098649/jquery-ajax-request-with-json-response-how-to) – Rcordoval Jun 09 '18 at 12:44

1 Answers1

0

You should set the contentType for JSON response.

response.setContentType("application/json");

Invoke flush() method on printWriter object after writing the json data.

writer.flush();
Gaurav Srivastav
  • 2,381
  • 1
  • 15
  • 18