Reputation: 23025
I am trying to submit some form data to Servlet
using JQuery
and retrieve the Servlet
response from the same JQuery
. Please have a look at the below code.
<%--
Document : index
Created on : Feb 23, 2015, 8:18:52 PM
Author : Yohan
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var form = $('#customItemForm');
function formSubmit(){
$.ajax({
url:'SampleServlet',
data: $("#customItemForm").serialize(),
success: function (data) {
$("#results").text(data);
var $textbox = $('<input type=text>').appendTo($('<div>')).appendTo($('#results'));
$textbox.attr("id",data);
//alert($textbox.attr("id"));
}
});
}
</script>
</head>
<body>
<form method="get" action="SampleServlet" id="customItemForm" onsubmit="formSubmit(); return false;">
Name <input type="text" name="name">
<button>Submit</button>
</form>
<br>
<div id="results"></div>
</body>
</html>
In the above code in JQuery section, I am trying to read the value I got from servlet, create a Text Input
in a DIV. My expectation was if I click the "Submit" button twice, then 2 text boxes; if I click the submit button thrice, then 3 text boxes and so on. Unfortunatly it is not happening here. Only one text box appear, all the time, replacing the previous one.
How can I fix this?
Upvotes: 0
Views: 188
Reputation: 24825
$.ajax({
url:'SampleServlet',
data: $("#customItemForm").serialize(),
success: function (data) {
$("#results").text(data); //replace with $("#results").append(data)
var $textbox = $('<input type=text>').appendTo($('<div>')).appendTo($('#results'));
$textbox.attr("id",data);
//alert($textbox.attr("id"));
}
});
}
you need to make the change above as .text() replaces the existing data in the div (so the previous run you did gets over-written)
Upvotes: 1