Can't receive response from servlet in Jsp file - java

I am trying to send some query from jsp file to servlet via post method and then get some modified result from servlet to jsp file.
I am able to complete first part successfully, but I cannot receive the response in jsp file.
Servlet post method is:-
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONObject js = <some method to get json>;
System.out.println(js); //works fine
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(js.toJSONString());
}
And my jsp code is:
<script>
function getData() {
$.post("MyServlet", {
query : "Wolf of wall street",
choice : "M"
}, function(response) {
alert("hello" + response);
});
}
</script>
The output is:
How can i get that json string ?

you are getting json as response need to stringify it.
<script>
function getData() {
$.post("MyServlet", {
query : "Wolf of wall street",
choice : "M"
}, function(response) {
alert("hello" + JSON.stringify(response));
});
}
</script>

Related

Ajax request call to the servlet doesn't return anything

This is my jquery function. It should pass to the servlet two value and get back an update value. I checked if the values are taken correctly and the two variables are filled correctly. Unforuntately I don't get nothing back.
$("#passengers").change(function(event){
var passengers = $("#passengers").val();
var price = $("#price").text();
$.getJSON('pricer', {passengers: passengers, price: price}, function(data){
$("#price").html(data);
});
});
here is the servlet
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String passengers = request.getParameter("passengers");
String price = request.getParameter("price");
String price_update = new Gson().toJson(this.pricerBean.calculatePrice(Integer.parseInt(passengers), Float.parseFloat(price)));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(price_update);
}
The main problem is I don't get any error...even one...the javascript console error is empty and even the servlet doesn't show any errors
try :
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data)); //here data is what you want to send
first try this simple :
response.getWriter().write("Hello");
in ajax :
$.get('pricer', {passengers: passengers, price: price}, function(data){
console.log(data);
});
then try to run and what it prints post me.
console.log() prints data in browser console.
use jquery getJSON() instead of get()
$.getJSON('pricer', {passengers: passengers, price: price}, function(data){
$("#price").html(data.price_update);
});
or with get
$.get('pricer', {passengers: passengers, price: price}, function(data){
// also validate data if it is not blank
var data = jQuery.parseJSON(data);
$("#price").html(data.price_update);
});

Passing custom objects from servlet to Jquery

i have a servlet my goal is to return a customer object from the process request, where i can then access this object in my jquery. Does anyone know how i can go about doing this?
e.g. myObject.getMethod()
Servlet Code:
Customer loginResult;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
//request.setAttribute("customerFirstName", loginResult.getFirstName()); //String Value
//request.setAttribute("customerID", loginResult.getCustomerID()); //IntegerValue
out.println(loginResult);
} finally {
out.close();
}
}
JSP CODE:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "get",
data: dataf,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
Can someone please assist me in resolving this issue, thank you for your help in advance.
Since you want to handle an ajax request using a Servlet, the best bet you have is writing the data of your custom object into the response. The easier way I found to accomplish this is using JSON. There are lot of libraries that handles JSON conversion from objects to Strings and vice versa, I recommend using Jackson. This is how your code should look like.
Servlet code:
import com.fasterxml.jackson.databind.ObjectMapper;
#WebServlet("/loginServlet") //assuming you're using Servlet 3.0
public class YourServlet extends HttpServlet {
//Jackson class that handles JSON marshalling
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
//login operation should be handled in POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Customer loginResult = ...; //process data and get the loginResult instance
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
//marshalling the data of your loginResult in JSON format
String json = OBJECT_MAPPER.writeValueAsString(loginResult);
response.getWriter().write(json);
}
}
Javascript code:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "post", //login action MUST be post, NEVER a get
data: dataf,
success: function(data) {
//shows the relevant data of your login result object in json format
alert(data);
//parsing your data into a JavaScript variable
var loginResult = JSON && JSON.parse(data) || $.parseJSON(data);
//now you can use the attributes of your loginResult easily in JavaScript
//for example, assuming you have a name attribute in your Customer class
alert(loginResult.name);
}
});
return false;
});
});
</script>
More info:
How to use Servlets and Ajax?
Parse JSON in JavaScript?

calling servlet from php page using ajax

i am trying to get response from servlet page and displaying alert on success. but its show me error always. i am not able to figure it out.
My ajax code:
$(document).ready(function() {
$("#srch").click(function() {
var txt1 = $("#store-qsearch").val();
alert(txt1)
$.ajax({
url : 'http://localhost:8080/searchengine/SearchDataServlet',
data : 'val='+txt1,
type : 'GET',
success : function(response) {
alert("Success");
// create an empty div in your page with some id
},
error: function(){ alert("error");
}
});
});
});
My servlet code:
public class SerachDataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String searchkey = request.getParameter("val").toString();
SearchInput searchinput = new SearchInput();
searchinput.searchkeys = searchkey;
System.out.println(searchkey);
SearchParser searchparser = new SearchParser();
searchparser.searchData(searchkey);
PrintWriter output = response.getWriter();
output.println("successs");
}
}
change this line data : 'val='+txt1, to data: { val: txt1},
see this for example

read jquery data send from AJAX to java servlet

Here is my AJAX code which triggers the Servlet 'CalculateLace'
laceTd.dblclick(function() {
var jsonObj= { jsonObj: [ {"rowID": $(nRow).attr('id')} ]};
$.ajax({
data: JSON.stringify(jsonObj),
contentType: "application/json; charset=utf-8",
traditional: true,
url: "CalculateLace"
});
});
And here is my Java Servlet code:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String id = req.getParameter("rowId");
//do something
}
But I keep getting String id as null. I also tried
String id = req.getParameter("id");
but to no avail. What am I doing wrong here?
Try this way -
var jsonObj= {"rowId": $(nRow).attr('id')};
and get rowID in your servlet this way - You can get library to parse your json here JSON.org
req.getParameter("rowId");

jquery ajax call returns error on successful call to a servlet

I have a servlet that adds a user to a file on the server side.
I invoke it with a jqueries ajax call.
I can see on the server that the method is being called correctly and my user is added, but the error callback is being invoked on the jquery call. All the status text says is error.
Using firebug the response seems to be empty. Why can I not get a success jquery callback?
//Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
String responseStr = "";
if(action.equals("addUser"))
{
responseStr = addUser(request);
}
System.out.println("Reponse:" + responseStr);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().println(responseStr);
}
private String addUser(HttpServletRequest request) throws IOException
{
Storage s;
s = Storage.load();
String name = request.getParameter("name");
String imageUrl = request.getParameter("imageUrl");
User u = new User();
u.setName(name);
u.setImageUrl(imageUrl);
s.addUser(u);
s.save();
return "success";
}
.
//javascript code
function addUser() {
var name = $('#name').val();
var imageUrl = $('#imageUrl').val();
var url = "http://ws06525:8080/QCHounds/QCHoundServlet?action=addUser&name=${name}&imageUrl=${imageUrl}";
url = url.replace("${name}", name);
url = url.replace("${imageUrl}", imageUrl);
$('#result').html(url);
$.ajax({
url: url,
success: function( data ) {
$('#result').html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error: " + textStatus);
alert("error: " + errorThrown);
}
});
}
Aaargh! Feel like an idiot. It's a cross site scripting issue.
I was testing the call to the server from the html file on disk so my browser address was
file://projects/myproject/content/Users.html <<< Fail
instead of:
http://myboxname:8080/appname/Users.html <<< Works
The actual code is fine...
use this for learn what is the problem, it will be better for get solution i think
error: function(e){
alert(JSON.stringify(e))
}
For one thing the string "success" isn't valid json. If your ajax query is expecting json, that would fail it.
What if you returned "{ \"success\": true }" ?
EDIT
It looks like from your ajax call that the response shouldn't be json, why is your return content type json?
If it is true that firebug shows no response, your problem must be in the java code that writes the response.

Categories

Resources