Data get from ajax null in jsp - java

I am able to get the data from ajax using system.out.println. However, I am unable to pass the data to servlet. It shows null always.
Here is my jQuery:
function expressCheck(number) {
var Self=[];
for(i=1;i<=<%=itemCodeList.size()%>;i++) Self[i-1] = document.getElementById("qtyGuestNumber_" + i).value;
$.ajax({
url: "ViewCategories.jsp",
data: {"expressData" : Self[number-1]}
});
};

Related

Passing javascript variable to servlet [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
How can I pass a var from javascript to a servlet. Yes I know you can use getParameter on the servlet side, but I first need to do some javascript stuff then from there it need to pass that new variable to servlet.
See my Javascript example:
function openBrWindowAndSubmit() {
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue); //returns empty
document.forms[0].submit();
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue); //works
}
As you can see in above example the first "alert" block returns empty, but the second one returns the correct encoded value because the document.forms[0].submit is already called. So is there a way I can get the second variable "textBodyValue" (which is outside of document.forms[0].submit) to the servlet? I'm calling this at the servlet side:
String test = req.getParameter("textBody");
Here's the JSP inside a form tag which calls the function on click:
<textarea id="textBody" name="textBody"></textarea>
<input type="button" onClick="openBrWindowAndSubmit();" value="Click Here to Preview Email">
Is there any workaround to this problem?
I've been trying to change the javascript function to:
function openBrWindowAndSubmit() { //v2.0
document.forms[0].target = "_blank";
document.getElementById("action").value = "view_template";
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue);
document.forms[0].submit();
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue);
$.ajax({
url: 'http://localhost:8080/restricted/comm/Email',
data: textBodyValue,
// processData: false,
// contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
Can this work? i'm getting an undefined error when reaching the $ajax tag?
As an idea. Dont know if its correct ;) but you can check it at the jQuery api page.
$('#idOfTheForm').on('submit', function(e){
e.preventDefault();
data = { key : val , key2 : val2 };
$.ajax({
type: "post",
data: data,
url : "",
success : function(response){
console.log("return code was 200");
},
error : function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
return false;
}

Consume Java RESTful webservice with jQuery

Consuming a RESTful Webservice with jQuery is what I want to achieve. After following this tutorial successfully. One of the file type is a JSON file. I want to read the values from the JSON file to be displayed on HTML file using jQuery. This is the code written so far to test this,but it is not giving the right output, what can I do?
This is the jQuery file
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/WMWebServiceApplication/webresources/com.mycompany.wmwebserviceapplication"
}).then(function(data) {
$('.discountCode').append(data.discountCode);
$('.rate').append(data.rate);
});
});
These are the parameters of the webservice created using Java
URL: http://localhost:8080/WMWebServiceApplication/webresources/com.mycompany.wmwebserviceapplication.discountcode
JSON parameters and values
[{"discountCode":"H","rate":16.00},{"discountCode":"M","rate":11.00},{"discountCode":"L","rate":7.00},{"discountCode":"N","rate":0.00}]
Request method
![GET(application/json)][3]
It's because you're receiving an array of objects in the JSON, so for example if you'd like to access the first element, you should write:
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/WMWebServiceApplication/webresources/com.mycompany.wmwebserviceapplication"
}).then(function(data) {
$('.discountCode').append(data[0].discountCode);
$('.rate').append(data[0].rate);
});
});
Here is a way to loop through the data and retrieve all of the values - http://jsfiddle.net/jayblanchard/cb62m/
for(i = 0; i < data.length; i++) {
$('.discountCode').append(data[i].discountCode + ' ' + data[i].rate + '<br />');
}

Passing name from input to servlet

I have an input:
Now this is one input from a div with several different inputs, there is a button called add exp which generates a new div with those inputs by calling href="#" and then jquery does the rest, only the name changes to for example institutionName0, institutionName1 etc so the fields get distinct. In my servlet I want to be able to get the actual input name like institutionName0 so I can check how much of the same fields are generated and that I can put in different values in those different fields.
You can send your form values to Servlet as a jSon object using ajax.
//Example
function onSubmit(divName){
document.forms["formName"]["formName_currentAction"].value = divName;
var theForm = $("form[name=formName]");
var params = theForm.serialize();
$.ajax({
type:"POST",
url:actionURL,
cache: false,
data:params,
success:function(data, textStatus, XMLHttpRequest){
//do something here
},
error:function(XMLHttpRequest, textStatus, errorThrown){
}
});

Access model object with JSTL

I'm currently trying to get to grips with AJAX, and have a problem accessing the model object.
What my test code does is get the value of the selected from a drop down list, when the button is pressed it passes this value to AjaxTest(), which attaches the param to the model, but I can't get seem to output the model object - I was wondering why this might be?
There is definitely a value for param.
<div id="result"></div>
<script type="text/javascript">
var param = document.getElementById("blah").value;
var loadUrl = "/ajax/" + param;
$("#button").click(function(){
$.post(loadUrl, function(data){
alert("Data Loaded: " + data);
$("#result").html("<p>Param: ${output}</p>");
});
});
</script>
#RequestMapping(value = "/ajax/{param}", method = RequestMethod.POST)
public #ResponseBody String AjaxTest(#PathVariable String param, final ModelMap model){
model.addAttribute("output", param);
return param;
}
I think you are getting a bit mixed up with what is client side and server side.
You java looks correct, but your js is trying to access a jstl expression ( ${output} ). The jstl expression won't resolve when the page is rendered, which will be before the Ajax request/response has happened.
Your js needs to work with the variable 'data' which is the data that your java adds to the model. Something like this:
$("#result).html("<p>Param: " + data.output + "</p>");
This assumes the model is json
Hope this helps
When page is first loaded, the JSP code executes. This code contains the following lines:
$("#button").click(function(){
$.post(loadUrl, function(data){
alert("Data Loaded: " + data);
$("#result").html("<p>Param: ${output}</p>");
});
});
So, the JSP EL code is interpreted by the container, and ${output} is replaced by the value of the output attribute. Since this attribute is null, the following HTML code is generated and sent to the browser:
$("#button").click(function(){
$.post(loadUrl, function(data){
alert("Data Loaded: " + data);
$("#result").html("<p>Param: </p>");
});
});
When you click on the button, the above JavaScript code executes. It sends an AJAX request to the ajax URL, and when the response comes back, it executes the callback function:
alert("Data Loaded: " + data);
$("#result").html("<p>Param: </p>");
So, the data received from the server is displayed in an alert box, and then the content of the HTML element identified by "result" is replaced by <p>Param: </p>.

Struts2 JQuery how to do onchange ajax

Let's say I have sj:autocompleter like this :
<sj:autocompleter id="idDistributor"
name="idDistributor"
list="%{idDistributorList}" label="ID
Distributor" indicator="indicator" />
when the value is changed, I'd like to pass the detail value to other text field like this :
<sj:textfield label="Nama Distributor" id="namaDistributor" name="namaDistributor" required="true"/>
where its value will be retrieved from struts back bean (FormAction).
How I could do this?
Really thanks in advance.
Mr.K
The following will send the autocompleter value to your action and set the value of #namaDistributor with the returned string:
$('#idDistributor').change(function(){
// Make the ajax request
$.ajax({
url: 'path/to/back-bean.action',
data: "autocompleterValue=" + $(this).val(),
dataType: "json",
success: function(data) {
// Set the inputs from the json object
$('#namaDistributor').val(data.distributor);
$('#namaPrice').val(data.price);
}
});
});
You can read more about the $.ajax() method here. The above json example assumes that your Action is creating a json object with the following format:
{"price": "123.40", "distributor": "XYZ Inc."}
You can read more about using json with Struts2 in this article.
you can do this with onSelectTopics.
Subscribe a topic like this:
<script>
$.subscribe('autocompleteSelect', function(event, data) {
var ui = event.originalEvent.ui;
$('#namaDistributor').val(ui.item.value);
});
</script>
and at it to your autocompleter
<sj:autocompleter id="idDistributor"
name="idDistributor" onSelectTopics="autocompleteSelect"
list="%{idDistributorList}" label="ID
Distributor" indicator="indicator" />
you can find an example for this in the Struts2 jQuery Plugin Showcase

Categories