How to use request/session attribute after jquery ajax request? - java

I have a form (comform) sent with this jquery ajax methode :
$(document).ready(OnReady);
function OnReady(){
$('#comform').submit(onComm);
}
function onComm(data){
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize(),
success: newComment('${cid}')
});
return false;
}
Inside the servlet's code I do this :
request.setAttribute("cid", methode());
(for short, the servlet use the form inputs' values to fill a table in my DB then I retrieve the id of this insert, put it as attribute as shown above and that's it !)
But even if I set 'cid' in the session scope, I give an empty string to 'newComment' instead of the int that 'methode()' actually return.. In fact, the ${cid} element in not refresh..
What can I do to get this attribute without reload the page ?
How can I use some result datas ?
Thanks

Related

How send information from forms without submit modal?

Right now i'm using jsp and bootstrap to make my front-end, and i have an option to make a new register inside a modal and this new register needs to be in my behind screen, in the past projects I used angular and it was very easy to do, but now using jsp I haven't any ideia to make it without submit my modal.
Is there a way to make it without submit my modal?
You can use Ajax, that way you can post the form to back-end to make what you need to do and than return the object to front-end.
Seeing your tags you're be able to make like that
Controller:
#Post
public void methodName(final T entity) {
.
.
.
result.use(Results.json()).withoutRoot().from(insertedObject).serialize();
}
Front:
$.ajax({
type : 'POST',
url : 'method url',
data : form.serialize(),
success : function(data){
// data is the object inserted
}
});

How to compare the datas from Website with Database

I have one scenario i.e., need to compare the values from Website with Database(MS Sql Table Values)
In my website having one datatable which is dynamic and the values changed based on Username.
I need to check whether the values present in datatable(website) should match with the Database.
Kindly let me know any ideas and code snippet for this.
You can use Javascript/Jquery that when a user change a value in datatable send a Ajax asyncron request to the java server and here check the values.
For example:
$( ".target" ).change(function() {
$.ajax({
type: 'POST',
url: 'myUrl',
data: JSON.stringify(myValues),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
})
});
Possibly I would load the data from MySQL -> Put it in Some POJO that mimics my datatable -> And preValidate the data -> put it in datatable.
Please put out some code which you have tried already.

how to get data from server without refreshing the page

I am new to web development. My job is to get data from the server and plot them using amcharts every 1 or 2 seconds.
This is what i have so far:
<form id="getdata" role="form" method="post" action=#routes.DataApplication.get_data()>
<input type="text" name="device" id="device">
<input type="text" name="type" id="type">
<button id = "submit" type="submit">Submit</button>
</form>
Once I enter device and type and click the submit button, it will run the Java method get_data(). The method will search the database and return data that matches the device name, but the thing is it will display is the data in another page, for example www.somepage/getdata. The above html is in www.somepage/data page.
I tried using jquery .post() but the thing is it requires an url, I tried passing /getdata to it but didn't work.
My question is: is there a way to save the data we get from the #routes.DataApplication.get_data() action without reloading the page?
By the way, I am using play framework to develop the webpage.
UPDATE
Ok, making some progresses now, I tried using ajax post, but the data return (in console) is like this:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
Here I got 11 objects. If i don't use ajax post (using the original post form method), I get 11 data points too.
Here is my code:
<script>
$('#driver').click(function(evt) {
var dataabc = $('form').serialize();
console.log(dataabc);
$('#errors').hide();
$.ajax({
type : 'POST',
data : dataabc,
url : '#routes.DataApplication.get_data()',
success : function(data) {
alert("good");
console.log(data);
},
error : function(result) {
setError('Make call failed');
}
});
return false;
});
</script>
What get_data() does is just take the user input data (which is the form) and get corresponding data from the database and return ok(node);. This node is JsonNode
Any help would be appreciated..
Since you are getting an array of objects back in javascript and it is stored in data. You can loop through it and display the content is some div tag.
Example:
Create an empty div to populate the data after a successful ajax call.
<div id="mytextarea"></div>
Then in your ajax success, instead of printing to console you would loop through the array and append the data to the innerHTML of the div tag like so...
var myTextArea = document.getElementById('mytextarea');
for (var x = 0; x < data.length; x++){
myTextArea.innerHTML = myTextArea.innerHTML + data[x].id + '<br/>';
}
Edit 1: I see you know your object's attributes so I updated the code to append just id to the text area.
It will be very helpful to tell us what exactly the url returns in response. Usually that should be XML or JSON.
You can use FireBug or any other developer tools to catch the response and post it here.
IT doesn't decide what to return - it's YOU!
If you'll return for an instance JSON object in your get_data() action, your AJAX will receive a JSON, check yourself:
public static Result get_data(){
ObjectNode node = Json.newObject();
node.put("hello", "world");
return ok(node);
}

Return Java list into jQuery object

Basically I have an Ajax request instantiated by a button where it is passed to my controller, and then that controller returns a list of objects. I initially was thinking whether this could be done by loading the returned ajax object into the JSTL forEach loop, but I think that cannot be done after some research.
This is my ajax request which loads sighting based on a value:
//edit the sighting based on the username value
$(this).on("click", ".edit_sighting", function(){
$username = +$(".edit_sighting").val();
$.get("${pageContext.request.contextPath}/getSighting/" + username, function(sightings){
// load returned object somewhere
});
});
This is my controller which handles the ajax request and responds returning a list of objects 'sighting':
#RequestMapping("/getSighting/{username}")
public #ResponseBody List<Sighting> getSighting(Model model, #PathVariable String username) {
List<Sighting> sightings = sightingsService.getSightings(username);
model.addAttribute("sightings", sightings);
return sightings;
}
And essentially I would like to load the returned objects into a for each loop or something that would display the object fields. for example: something like that.
My for each loop:
<c:forEach var="sighting" items="${sightings }">
<c:out value="sighting.name"/> <!-- load some sighting value -->
</c:forEach>
So essentially what I am trying to achieve is, load multiple or one 'sightings' into a modal type thing when a button is instantiated.
You can't use JSTL for this since JSTL is executed on the server before a page is sent to the client. What you could do is render the HTML on the server and return a HTML document (instead of JSON). So the solution would be to define a JSP view which uses JSTL to render the list and change the AJAX request to accept HTML.
The other solution is to add a JavaScript based template engine and do the template rendering client side.
Or do it manually with jQuery. If you have
<ul id="sightings"></ul>
then you can
var sightings = $('#sightings');
sightings.empty();
$.each(sightings, function(index, e){
var li = $('<li>');
li.text(e);
sightings.append(li);
});
The response to the ajax request is returned to the client, which does not have access to server side mechanisms such as JSTL. The code should use Javascript/jQuery on the client side to display the new DOM elements.
So if you had the following HTML on your page:
<ul id="sightings"></ul>
The callback would look like:
$(this).on("click", ".edit_sighting", function(){
$username = +$(".edit_sighting").val();
$.get("${pageContext.request.contextPath}/getSighting/" + username, function(sightings){
var output = "";
for(var i = 0; i < sightings.length; i++){
output =+ "<li>" + sightings[i].name + "<\/li>";
}
$("#sightings").append(output);
});
});
This will build a String containing HTML which has an li for each sighting. The HTML is then appended to the DOM as children of the #sightings ul.
Since you are using ajax so the page will not reload once your request returns the response so anyway this code
will not work.
what you can do is instead of sending a list you can send a JSON array as response and each array element will have a JSON object having all the required properties and this array can be iterated after the response is received.

How to use struts tag in javascript

I'm trying to get value from Action using Ajax request, but I'm having problem in using struts tag in javascript to show the value.
Javascript code:
dojo.xhrPost({
url: "dashboard"
,content: myParameterscomp
, handle: function(response, ioargs) {
if (ioargs.xhr.status == 200)
{
var data = "<s:property value='#request.consumptionData'/>"
console.log(data);
}
}
,error: function (data) {
handleError(data.description);
}
});
Java code:
Map request = (Map)context.get("request");
request.put("consumptionData", 43);
I'm getting the value of data as <s:property value='#request.consumptionData'/> on console instead of 43. I'm using struts2. My javascript code is in JSP file. Could anyone please tell me how can I show the value?
You seems to be calling /dashboard page via Ajax from your homepage. And expecting it to send you request attribute consumptionData. This won't work as your JSP does not contain required data. You need to put data in JSP and then fetch the same in Ajax. Convert your response to JSON. The simplest way of doing this would be to put following like of code in your Ajax response JSP.
Dashboard.jsp
{"consumptionData": < "<s:property value='#request.consumptionData'/>"}
And in main page when you load this JSP via ajax, you can parse this JSON output and use data in Javascript.
var json = JSON.parse(response);
var data = eval(json.consumptionData);
Code in browser accepts JSON. You could serialize you request as JSON and embed in you JavaScript file. For example:
var data = <%= toJson(request.get("consumptionData")) %>
If the data is simplely Integer values, you can even directly put the value in the code:
var data = <%= request.get("consumptionData") %>
The syntax could be vary (I'm not familiar with struts tag), but the idea is the same.

Categories