How can we show the result in same page using ajax? - java

Here is my calculatioform.jsp which accept two number.
when I press submit button it will display the result which contains addition, subtraction, multiplication and division in the same calculationFrom.jsp using ajax and jquery.
the jquery and ajax I am using to get the response is.
<script type="text/javascript" >
$(document).ready(function(){
$(".button").click(function() {
var str = $("form").serialize();
var str = $("form").serialize();
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
dataType:"json",
success: function(data) {
var msg = data.val1 + " + " + data.val2 + " = " + data.sum;
alert(msg);
}
});
return false;
This is my calulator.jsp page on clicking submit button the request go to this
page.It will take two parameter from form and do calculation.The input value is
store in Val1 and Val2. based on this i calculate the result.
String result = "({";
result += " val1 : " + val1 + ",";
result += " val2 : " + val2 + ",";
result += " sum : " + (val1 + val2) + ",";
But this code is not working. what I need to do so that the code will work.

you are not defining data in your success callback function definition
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
success: function(data) { //you need data defined
Depending on what data is being returned you might need to specify the return type by using dataType option
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
dataType:"json",
success: function(data) {
//access properties through data
var msg = data.val1 + " + " + data.val2 + " = " + data.sum + '\n';
Additional Edit
Also it looks like you have the click event attached to the submit button which is probably causing the script to submit to itself or whatever page you have set in the action attribute, you need to have it cancel the default action by using preventDefault
$(".button").click(function(e) { //e will hold the event object
e.preventDefault() //prevents the default action of the event,
//in this case the form submission
var str = $("form").serialize();
you may also be getting a parse error, you can set an error callback as well
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
dataType:"json",
success: function(data) {
var msg = data.val1 + " + " + data.val2 + " = " + data.sum;
alert(msg);
},
error:function(xhr,errormsg) {
alert(errormsg);
}
});

<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
var marks1=$("#marks1").val();
var marks2=$("#marks2").val();
var option=$("input:radio:checked").val();
var str = $("form").serialize();
$.ajax({
type: 'GET',
url: 'Operation',
data:{ marks1:marks1,
marks2:marks2,
option:option
},
success: function(data){
//Do something
}
});
});
});

You can get a response by your web method
$(function(){
$(".button").click(function() {
var str = $("form").serialize();
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
success: function(response) {
}
});
});

Related

Selenium JavascriptExecutor - Unexpected token at javascript algorithm

I try to execute this java code
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement hoverElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[#id = 'demo']")));
//trigger mouseover on hoverElement
//return innerHTML of element which appear
String jsAlg = "" +
"if(document.createEvent){" +
"var evObj = document.createEvent('MouseEvents');" +
"evObj.initEvent('mouseover', true, false);" +
"arguments[0].dispatchEvent(evObj);" +
"}else if(document.createEventObject){" +
"arguments[0].fireEvent('onmouseover');" +
"}" +
"var target = new XPathEvaluator().createExpression(//div[#id = 'target'])" +
".evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)" +
".singleNodeValue" +
"return target.innerHTML;";
String targetHTML = (String)((JavascriptExecutor)driver).executeScript(jsAlg, hoverElement);
System.out.println(targetHTML);
I try to execute this js on this html
<html>
<head>
</head>
<body>
<div id="demo" onmouseover="mouseOver()" onmouseout="mouseOut()">Mouse over here</div>
<script>
var node = document.createElement("div");
node.id = "target";
node.innerHTML = "mouse over active";
function mouseOver() {
document.body.appendChild(node);
}
function mouseOut() {
document.body.removeChild(node);
}
</script>
</body>
</html>
I get an error when try to execute jsAlg: javascript error: Unexpected token '}'
What is wrong at jsAlg?
Edit 1
The problem is at var target = ....
I replaced that with var target = document.getElementById('target'); and work.
But I need to use XPathEvaluator because, I execute this js in other case, where target don't have an id and can identify it with xpath.
Edit 2(I found the real problem)
The problem was at .createExpression(//div[#id = 'target'])
It should be .createExpression(\"//div[#id = 'target']\")
Parameter should be between "

Ajax - API Endpoint - Is this the right way to do?

I'm having a encoding issue when I send a AJAX request to an API Endpoint.
I have this Endpoint in the code below using Java Spring:
#Autowired
ApiKeyRepository apiKeyRepository;
#RequestMapping(value= "/weather/{cityName}/{fuCity}/now", method = {RequestMethod.GET}, produces="application/json" )
public ResponseEntity<Weather> getWeatherNowByCityName(#PathVariable(value = "cityName") String cityName, #PathVariable(value = "fuCity") State fuCity) throws JSONException, ParseException, java.text.ParseException {
String newCityName = cityName.toLowerCase();
try {
newCityName = URLDecoder.decode(newCityName , "UTF-8").replace(" ", "%20");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String weatherEndpoint = "/api/v1/locale/city?name=" + newCityName + "&state=" + fuCity.toString();
String appToken = apiKeyRepository.getByservice("climaTempo");
URL weatherDomain = new URL("http://apiadvisor.climatempo.com.br" + weatherEndpoint + "&token=" + appToken);
/// From here I send a JSON Request to the 'weatherDomain' to get the Weather from the city and her state that I get from the EndPoint Parameters
}
And I send this jQuery Ajax request to the Endpoint:
var uf = $("#colWeather #selectState").val();
var city = $("#colWeather #selectCity").val();
$.ajax({
url: host + '/weather/' + city + '/' + uf + '/now',
type: 'GET',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async: true
}).done(function (JSONReturn) {
//Actions with JSONReturn
});
But here in Brazil we have some cities with accents and cedilla like "Avaí" from "SP", "Mairiporã" from "SP" and "Missão Velha" from "CE".
If I send to the Endpoint an URL like "/weather/Americana/SP/now" or "/weather/Piracicaba/SP/now" the Endpoint gets the JSON return without problems.
But if I send to the Endpoint an URL like "/weather/Mairiporã/SP/now" or "/weather/Avaí/SP/now" the ClimaTempo API returns a null JSON and I get a NullPointerException.
I'm thinking that is a problem with the accents, but I can't send just "/weather/Mairipora/SP/now" without the accents because the ClimaTempo API demands that the city name must go with the accents, otherwise it returns a null JSON...
What am I doing wrong?
You need to encode and decode your characters.
Encode in JavaScript
Instead of url: host + '/weather/' + city + '/' + uf + '/now', go for
url: host + '/weather/' + encodeURIComponent(city) + '/' + uf + '/now'
Decode in Java
Instead of String newCityName = cityName.toLowerCase();, go for
String newCityName = URLDecoder.decode(cityName, Charsets.UTF_8.name()).toLowerCase();

How to get selected value from json list on java

I've list from db and put in json list with checkbox and the value. I need the value for insert to table db. So, how to get value from the selected checkbox in java? Thanks a lot.
In JSP File
function refreshList() {
var collection = "";
collection = collection
+ " <table><thead><th class='LIST'><span><label>Selection</span></label></th><th class='LIST'><span><label>List</span></label></th></thead><tbody>";
var isnew = $("input:radio[name=isnew ]:checked").val();
var string = "";
$.getJSON('${pageContext.request.contextPath}/master.do?reqcode=refreshList', {
'isnew ' : isnew
}, function(result) {
$.each(result,function(key,value) {
string = string + "<tr><td> "
+ "<input id='id' type='checkbox' value=" + key + "/></td>" + "<td> " + value
+ "</td></tr>";
});
collection = collection + string + " </tbody></table> ";
$('#collectionid').html(collection);
});
}
<div id="collectionid"></div>
You need to have a name attribute on the checkbox.
<input name="chkBox" type="checkbox" value="xxx" />
You can get the checkbox value from servlet request object as shown below:
String[] values = request.getParameterValues("chkBox");

Valid AJAX request with Spring MVC

I'm trying to send an AJAX jQuery request to my Spring MVC Servlet and got some problems. I read some articles already but they didn't help me :(
So I have this ajax request:
$.ajax({
url : "add_news",
type : "POST",
dataType : 'json',
contentType : 'application/json',
mimeType : 'application/json',
data : JSON.stringify({"category": categoryName, "name": newsName, "data": newsData}),
success : function(data) {
$("#list_news").append(
data.id + " : " +
data.name + " - " +
data.created + " ; " +
data.data + "<br>");
}
});
Controller is:
#RequestMapping (value = "/add_news", method = RequestMethod.POST)
public #ResponseBody News addNews(#RequestParam String category, #RequestParam String name, #RequestParam String data) {
System.out.println("category " + category);
System.out.println("name " + name);
System.out.println("data " + data);
NewsCategoryDict c = new NewsCategoryDict();
c.setId(66);
c.setName("misc");
News response = new News();
response.setCategory(c);
response.setId(60);
response.setName(name);
response.setData(data);
response.setCreated(new java.util.Date());
return response;
}
I don't even get System out - so my first problem is with url. "add_news" is not a jsp - just a logic to get a record from server.
Second problem (if I undestand it right) in entry params. I have to use #RequestBody to get data from the client as Java POJO and send this POJO back with some additional info. But I don't understand how to write JSON body in AJAX.data right to make it valid.
Please help me.
EDIT
Ok. I find a moment. If I use GET in $.ajax AND set RequestMethod.GET in controller handler method - method is invoked (with POST - no actions). So why POST is not working ??
Remove JSON.stringify() from post data:
$.ajax({
url : "add_news",
type : "POST",
dataType : 'json',
contentType : 'application/json',
mimeType : 'application/json',
data : {"category": categoryName, "name": newsName, "data": newsData},
success : function(data) {
$("#list_news").append(
data.id + " : " +
data.name + " - " +
data.created + " ; " +
data.data + "<br>");
}
});

PlayFramework and jquery chart

i'm trying to use https://github.com/thegrubbsian/jquery.ganttView
in play 1.2.4
already check JQuery GanttChart - Apply Data
but my problem is how to renderJSON to the view,
i have try a simple one that is renderJSON("Hello"); and capture in the view, the problem is that i only manage to download a file like 4fporLKs.part1 that have inside Hello :(
can some one explain me how to do it
thanks
other guy is working in the same as i, but haven't got it
<script type="text/javascript">
$(function ()
{
$("#ganttChart").ganttView({
data : 'dataUrl: "data.json"',
slideWidth: 900,
behavior: {
onClick: function (data) {
var msg = "You clicked on an event: { start: " + data.start.toString("M/d/yyyy") + ", end: " + data.end.toString("M/d/yyyy") + " }";
$("#eventMessage").text(msg);
},
onResize: function (data) {
var msg = "You resized an event: { start: " + data.start.toString("M/d/yyyy") + ", end: " + data.end.toString("M/d/yyyy") + " }";
$("#eventMessage").text(msg);
},
onDrag: function (data) {
var msg = "You dragged an event: { start: " + data.start.toString("M/d/yyyy") + ", end: " + data.end.toString("M/d/yyyy") + " }";
$("#eventMessage").text(msg);
}
}
});
//$("#ganttChart").ganttView("setSlideWidth", 600);
});
</script>
"hello" is not well formated json string, try:
renderJSON("{\"hello\":\"world\"}");
Also check Play's documentation for controllers to see how render ie. json from List (paragraph: Return a JSON String)

Categories