0

JSP

<div id="feedback" class="statusbar"></div>

In jQuery

$("#categorySave").click(function(){        
$getCode = document.getElementById("catCode").value;
$getName = document.getElementById("catName").value;
$getDesc = document.getElementById("catDesc").value;
$getDepID = $("select option:selected").val();

$(':text').val('');

$('#feedback').html('<img src="images/loading.gif"/>Processing....');

$.post("CategoryOperation", {
    catCode:$getCode,
    catName:$getName,
    catDesc:$getDesc,
    catID:$getDepID
}, function(html) {
    $("#feedback").html(html);         
});
});

In Servlet (CategoryOperation)

out.println("<div>Record Inserted!</div>");

When I press the save button (id=categorySave), it shows the message in div (id=feedback) as record inserted. The above code it working fine. But I want a little change now, that When record is inserted successfully, it shows result on text fields rather than on div (id=feedback).

Suppose,CategoryOperation (Servlet) print the followings two after process,

out.println("Record Inserted!");
out.println("1");

Now I want to show the above two output in the text fields respectively, and they have the following ID

id="Result"
id="Key"

How can I do this, in above jquery code snippet , by writing the following code or any other easy way

$('#Result').val();
$('#Key').val();
Both FM
  • 770
  • 1
  • 14
  • 33

1 Answers1

1

You need to let the servlet return a parseable object format instead of plain text, such as JSON or XML. jQuery has builtin support for both.

Here's a JSON example:

String json = String.format("{\"result\": \"%s\", \"key\": \"%s\"}", "Record Inserted!", "1");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

(Google Gson may make JSON formatting much easier)

which needs to be processed as follows:

function(data) {
    $("#Result").val(data.result);
    $("#Key").val(data.key);
}

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555