Print AJAX Success Data? - java

I have a problem with printing Ajax success data.
success: function(data){
alert(need to print it here);
}
How it comes when I access
console.log(data.responseText);
{"success":false,"errors":{"text":["Some text.","some more text"]}}
How can I alert "Some text" or "some more text" now?
Thanks

alert data
success: function(data){
alert(data);
}
write to div tag
<div id="mydiv"></div>
success: function(data){
document.getElementById("mydiv").innerHTML += data;
}

Say you have a div to print the result like
<div id="res_div"></div>
You can access the contents by
console.log(data.responseText.errors.text);
You just try the following to print the content to that div
$("#res_div").text(data.responseText.errors.text);

Just drill down the data object to the errors.text array and loop through them, like this:
$.each(data.responseText.errors.text, function(index, item) {
alert(item);
});

Related

Data get from ajax null in jsp

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]}
});
};

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;
}

Jquery autocomplete issue

I am new to jQuery and am trying to use the autocomplete widget with an ajax call to my database.
I am able to call the database, returned ArrayList of string values, and converted the response as a JSON object using org.codehaus.jackson.map.ObjectMapper (Do I need to use something else?).
When I put an altar, I can see results as pure strings with comma delimiter, but am not able to see a suggestion list with autocomplete.
Java code that returns the JSON object using org.codehaus.jackson.map.ObjectMapper:
response.setContentType("application/json");
response.setHeader("cache-control", "no-cache");
ArrayList polNo = doa.getPolicyData(ajaxForm.getPolicyNumber());
ObjectMapper mapper = new ObjectMapper();
OutputStream out = response.getOutputStream();
mapper.writeValue(out, polNo);
JavaScript code:
$( "#policyNumber" ).autocomplete({
source: function (request,response){
$.ajax({
type: "POST",
url: "/NB/AjaxSubmit.do",
dataType: "json",
data: {policyNumber: request.term},
success: function (data) {
alert(data);
}
});
},minLength: 3
});
alert data showing as : TMA412732,TMA412733,TMA412734
In above code, I have returned ArrayList of string values and was able to show in autopopulate. I have enhanced the above code to return list of person objects that has first name, last name etc. Now when user typing the firname or last name in the autopopulate , I would like to suggest First name, LastName Middle.
Could someone help to enhance this? Thanks!
success: function(data) {
response(data);//u forgot to set data on response
}
Change success function like
success: function (data) {
response(data); //u forgot to set data on response
}

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