Here is my need:
I show a popup in which some text boxes are displayed and a submit button. Now when user presses submit I need to insert values inserted in textboxes to the db. I have done this but I also need to show newly added values in the page it self without refreshing it. I tried this using Ajax but it requires lot of writing html tags in servlet like
printWriter.print("<table><tr>"+data.getId()+"</tr></table>");
and then show whole response in a div tag. Is there any easy way of diong this?
A better way to do it would be for the servlet to return some JSON or XML to the page and then have some client-side javascript that updates the view. If your data is simple then you may not even need JSON or XML - maybe a comma-separated list of values is enough for your use case.
Doing it this way means that your servlet doesn't need to worry about writing HTML tags in the AJAX response, and your client-side doesn't need to worry about malicious HTML coming back from the server (always a possibility if user input is involved).
Using jQuery it is pretty simple. Something like this:
$('#form_id').submit(function() {
$.ajax({
type: "POST",
url: "/YourServlet",
data: $(this).serialize(),
success: function(msg){
$('#result_div_id').html( "Data Saved: " + msg );
}
});
return false;
});
Here are jQuery docs.