Reputation: 284
weird problem here I can't seem to solve.
I'm working in Eclipse Java EE, I have a servlet called Process (mapped to /process)
There is a link to process
<a href="process?intent=order">Checkout</a>
Within process is a doGet method, verifying there is a user logged in, which redirects to a checkout page. (this works) The checkout page contains items, each with an individual input, and I have a seperate doPost method which updates the DB.. obtaining the input to update as follows
<input id='ID created in servlet' value='decided in servlet'>
followed by
<button id="update">Button</button>
I have the following JS
var json = [];
$('#update').click(function(){
$('.items').find('input').each(function(){
var tmp = "{id:" + $(this).attr('id') + ",quantity:" + $(this).val() + "}";
json.push(tmp);
});
$.ajax( {
url : 'process',
type : 'POST',
data : json,
dataType : 'json',
success: function(data) {
alert("success");
}
});
});
So, two questions I guess.
First, this is sending a request to a different servlet, in a different project. However when accessed using a doGet, it works. (I have different code for a doPost) Is there any reason it's not recognizing the doPost method within my Process.java file? What could cause it to search for another servlet?
Second, I know what to do once I get the data in the servlet, but I don't know how to actually access the data. It's passed through jquery in 'data:', then how would I access it in the servlet?
Upvotes: 0
Views: 525
Reputation: 1252
First Question:
If i have understood right, Your problem is that "when you try to send a post request using AJAX (inside a jquery function), you are not hitting the desired servlet".
Solution:
You need to append the name of your project to the url.
So lets say your servlet is placed in project named "SomeProject"
and the servlet is mapped to url named "servletProcess"
.
So your jQuery should look something like this:
var json = [];
$('#update').click(function(){
$('.items').find('input').each(function(){
var tmp = "{id:" + $(this).attr('id') + ",quantity:" + $(this).val() + "}";
json.push(tmp);
});
$.ajax( {
url : '/SomeProject/servletProcess',
type : 'POST',
data : json,
dataType : 'json',
success: function(data) {
alert("success");
}
});
});
This should fix the problem :)
Second Question: try this Similar Query
Upvotes: 1