Reputation: 463
I want to send some data from JavaScript to Java servlet with help of JSON. But I have problem with it.
This is my JavaSript code:
var myData = {"someNumber":34,"someDate":"May 22, 2014 12:00:00 AM","expiryDate":"May 29, 2014 12:00:00 AM","anotherNumber":3,"customerNumber":56,"name":"John Dow","type":"notype","someSize":"XXL","noMonth":11,"notes":"some notes here","colour":"Black"};
$.ajax({
url : "customerAdd",
type: "get",
data: {"myData" : JSON.stringify(myData)},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(msg) {
alert(msg);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("jqXHR: " + textStatus);
console.log("textStatus: " + textStatus);
console.log("errorThrown: " + errorThrown);
}
});
This is my Java code:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
Gson gson = new GsonBuilder().create();
Customer customer = gson.fromJson(request.getParameter("myData"), Customer.class);
System.out.println(customer.toString());
}
In result I get an error in JavaScript:
"textStatus: parsererror"
"errorThrown: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"
What's wrong with my code?
P.S. I create myData in JavaScript by this way:
var myData = {
someNumber: + $("#someNumber").val(),
someDate: $("#someDate").val(),
expiryDate: $("#expiryDate").val(),
anotherNumber: + $("#anotherNumber").val(),
customerNumber: + $("#customerNumber").val(),
name: $("#name").val(),
type: $("#type").val(),
someSize: $("#someSize").val(),
noMonth: + $("#noMonth").val(),
notes: $("#notes").val(),
colour: $("#colour").val() };
Upvotes: 0
Views: 375
Reputation: 472
If the servlet method is not returning any json content to ajax, remove the
dataType: "json", from ajax call in javascript.
Upvotes: 0
Reputation: 463
I've found my mistake. I shouldn't put
dataType: "json",
attribute in $.ajax, because I don't expect JSON data back from server. I've just removed it.
Thank you Lee Bee and Tony for your advices.
Upvotes: 1
Reputation: 492
Here is a JSON.stringify exemple :
JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}'
You should remove the quots on the name of parameters, or could use a javascript object.
You should create your object like that :
var myData = new Object();
mydata.someNumber = $("#someNumber").val();
...
edit :
It's seems your trying to get a response in the ajax call, but your java code doesn't response anything, maybe you may try to debug it. and try to see if the java code is triggered ?
Upvotes: 2