Oxenarf
Oxenarf

Reputation: 278

Handle request and response between ajax and java servlet

I'm trying to handle the request/responde between ajax and a servlet: The user click on a Google map marker, and through ajax he call the comment relative to the marker using his id.

this should be the Ajax code

 function infoCallback(infowindow, marker) {
    return function() {
        $.ajax({
            type: 'POST',
            url: 'commentListener',
            data: {
                id: marker.id,
                comment:$('#comment').val()
            },
            success:function(data){
                var comment = $('#output').html(data);
                infowindow.setContent(comment);
                infowindow.open(map, marker);
            }
        });
    };
}

and this should be the Servlet code

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    long id = Long.parseLong(request.getParameter("id"));
    String comment = //comment relative to the id
    /*Way to send the comment to the infowindow*/
    response.getWriter().write("{comment:"+comment+"}");
}

Sorry if all this is not so clear!

Upvotes: 0

Views: 2878

Answers (1)

(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

SOLVED

Using PrintWriter

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    long id = Long.parseLong(request.getParameter("id"));
    String comment = //get comment by id
    try {  
        PrintWriter out;
        out = response.getWriter();  
        out.print(comment);
    } catch (IOException e) {  
        e.printStackTrace();  
    }
}

and this is the ajax

function infoCallback(infowindow, marker) {
    return function() {
        $.ajax({
            type: 'POST',
            url: 'commentListener',
            data: {
                id: marker.id,
            },
            success:function(result){
                infowindow.setContent(result);
                infowindow.open(map, marker);
            }
        });
    };
}

Upvotes: 1

Related Questions