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
Checkout
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?
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
Related
Is there a way to return a dynamically server-side generated file, which was fetched from a ajax post structure?
Writing a small web mvc project, which generates a list of data(the data is generated from a complex aggregation query and cannot be called from id or whatsoever), and come up to the part on which i want to export some selected parts to a file and download it.
How does it work:
1. On the page i select some fields with key data(using JQuery DataTable)
2. Send it to a controller(Spring to be precise)
3. Generate a bytestream and return it as a HTTPResponse with "Content-disposition", "attachment" header.
Thing is that i select the lines and form the needed data using JQuery->Ajax, so the result of the Controller->Post stays inside the javascript part, not giving me a "Save as...".
I'm already thinking of a temporary directory or something, but saving option for the last.
Unfortunately you can not get file through ajax, but you can achieve it by generate form dynamically and submit it. As per our comment discussion for generate form and submit it you can do something like this.
function autoSubmitForm(method, url, post_data) {
var element = document.getElementById("virtual_form");
if(element != null )
{
element.parentNode.removeChild(element);
}
var form = document.createElement("form");
form.setAttribute("id", "virtual_form");
form.setAttribute("style", "display:none;");
form.method = method;
form.action = url;
for(i in post_data)
{
var element=document.createElement("input");
element.value=post_data[i];
element.name=i;
form.appendChild(element);
}
document.body.appendChild(form);
form.submit();
}
autoSubmitForm('POST','your_url.php',{id:"xyz",other_input:"input value"});
Here {id:"xyz",other_input:"input value"} is object of post data you can define it dynamically pair of field name and value of field. pass it in function.
I am unable to get the string response from the java function to the ajax call. I am using structs2 . I have wrote a java function that returns a string. the function works properly. but there are some unknown error in the ajax call.
following is my jquery ajax call
<pre>
function saveMyId(){
$.ajax({
url : contextPath+'/action/setMyId',
data: {
myCode:$("#myCode").val(),
myId:$("#myId").val()
},
type : 'post',
async: false,
success : function(data) {
alert(data);
if(data=="success"){
$( "#dialog" ).dialog("close");
$('#myId_Validator').text("");
}
else{
$("#myId").val("");
$("#myId_Validator").val("ID Already exists. Please Choose different one")
}
},
error: function (request, status, error) {
alert("Something went wrong. Please try again later");
}
});
and my java function is
public String setMyId() throws SQLException {
IdAllocationVO idAllocationVO = new IdAllocationVO();
MyIdServices myIdServices = new MyIdServices();
logger.debug("set My Id , myCode :"+this.myCode);
idAllocationVO.setMyCode(myCode);
idAllocationVO.setMyId(myId);
int response= myIdServices.getMyIdCount(myId);
System.out.println("response:"+response);
if(response==0){
myIdServices.setSenderId(idAllocationVO);
return "success";
}
else{
return "fail";
}
}
I am using structs 2
and the structs.xml tag is
<action name="setMyId" class="com.id.myIsservice.struts.IdAction" method="setMyId">
</action>
The function setMyId() is working correctly. I have checked everything by printing each line. But my issue is the ajax call gets the result as an error. so it alerts the error message "Something went wrong. Please try again later". Why it is so?
there are three steps you can try to use for finding the reason:
1、If your ajax call is correct?
firebug or other page dubugger can show you~
2、When the 1st step is correct, check the java function to see if it gets the request from page and responses the right result to page
IDE debug tools will help you~
3、Check what results are got by page
through firebug you can see the response details, like 'status' and others..., findout if the string has been got~
PS:
I see, your java code throw exceptions directly without using try/catch. It's not a good way for users' use~ I suggest you to add try/catch code, with whith maybe help you find error quicker~
Good Evening, I try to do a checkbox which embedded in a JSP page. I use document.getElementByID("checkbox") in the JSP javascript function. How to pass the variables in the javascript function to another java file without passing it through url for security concern?
This is Checkbox Function:
var checkbox = document.getElementById("chbx");
function foo(){
if(checkbox.checked=true){
//passThisVariableToAnotherJavaFile-isChecked
}
else {
//passThisVariableToAnotherJavaFile-isNotChecked
}
};
This is Java File:
public class CheckBoxEvent{
if(isChecked) {
//then whatever
} else if (isNotChecked) {
//then no whatever
}
}
I am a newbie is this jsp stuff, I used to be doing this in PHP but everything mixed-up in my mind when there is a HashMap appear in the java file. Well, need some hints and help.
Thank You
How to pass the variables in the javascript function to another java file without passing it through url for security concern?
You have two options here and in both the cases you need to send the value to the server for processing :
An AJAX POST or GET request. This looks more appropriate to your requirement. You can get an example here.
Submit the form using POST.
Read here When do you use POST and when do you use GET?
In both the cases , there will be a Servlet/JSP/Controller handling the request in the server. You can call the methods in your Custom Java class with the request parameters.
when you do var checkbox = document.getElementById("chbx"); you are doing it at client side. Now if you want to propagate this value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-
1)Make an AJAX call. (You can also use jquery here to make AJAX call).Here is
the small example, you can find ample on google
$.ajax({
type: 'GET',
dataType: 'json',
url: servlerURL,
success: function(reply) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
or
2)Submit the form
I am trying to post image to user wall using javascript FB.api. Image is generated from a java servlet dynamically, but due to asynchronous behavior before the image is generated it passes control below the block to post image to Facebook part.
I want either
how can I make fb.api post to Facebook call from servlet?
how to deal with this behavior so that control will not passes below before image generation?
note servlet is working file and generating image .
var imgURL="http://xxx.xxx.xxx.xxx:8084/myapps/app1?monthly="+monthly+"&recent="+recent+"&likes="+likes;
//var imgURL="http://xxx.2xx.xx6.1x8:8084/WebApplication6/image";
alert('image');
//var imgURL="https://graph.facebook.com/100000329585395/picture";
var img = document.createElement('img');
img.src =imgURL;
document.body.appendChild(img);
FB.api('/me/photos', 'post', {
message:'image',
url:imgURL
}, function(response){
alert('here');
if (!response || response.error) {
alert('Error occured'+response.error);
} else {
var postId = response.id;
alert(postId);}
});
Check RESTFB Api which is a Java API. You can use this instead of Javascript API.
An applet developed outside our company just started failing for some users this week. Apparently it was because of the latest version of java (1.6u24) that auto updated. Is there a way to capture what version of java the user opened the applet with?
You can use System.getProperty("java.version") to get that information. This is an example applet that uses it and the About page has the source.
You can use System.getProperty, specifically :
System.getProperty("java.version")
For a list of possible key value, see : getProperties()
http://pscode.org/prop/?prop=java.version%2Cjava.vm.version
Using the answers from another question, I ended up writing the code below. When the page loads, I get the user's java version then use an ajax call to save it where ever I need to. The part I used was the reference to the deployJava.js from Sun.
$(document).ready(function() {
var jVersion = "";
for (var i = 0; i < deployJava.getJREs().length; ++i) {
jVersion += deployJava.getJREs()[i];
}
var url = 'saveJavaVersionAction.jsp';
var params = 'version=' + jVersion;
$.ajax({
url: url,
data: params,
success: function(html) {
$("#results").append(html);
}
});
});