I’m going to implement a searching function for a sms managing system, where the user can enter a name(keyword) and get relevant information.
This is the code that i wrote in “InstantSMS.jsp”
$("#search").click(function() {
var keyword = $("#customerName").val();
$.ajax({
type : "GET",
url : "SearchingClass",
data : {
key : keyword
}
}).success(function() {
$.getJSON('SearchingClass', function(data) {
$("#resultTable").html(data.messageRes);
});
})
.error(function(request, error) {
$().toastmessage('showWarningToast', "Error! ");
});
});
Here the ‘SearchingClass’ is the name of the servlet.
this is the code of ‘SearchingClass.java’
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String keyword = request.getParameter("key");
SmsMessagesService search = new SmsMessagesService();
ArrayList<Customers> result = new ArrayList<Customers>();
System.out.println("For testing Keyword is ::: "+keyword);
result = search.searchCustomer(keyword);
String table = "in here i'll generate a code to draw a table using html"
Map<String, Object> data = new HashMap<String, Object>();
data.put("messageRes", table);
// Write response data as JSON.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
Now the problem is after i press the search button the searching process or the doGet method run 2 times.
In 1st run output
“For testing Keyword is ::: john ”
2nd run
“For testing Keyword is ::: “
I think that the 2nd run is happening because of “$.getJSON()” method.
How to avoid this ?
How can i use $.getJSON() method only to get the “String table” but not to run the “doGet()” method ?
Is there another way to get a string from servlet to jsp using ajax ?
Can i pass this keyword using $.getJSON() method ?
Thank you !
You can use shorthand AJAX call.