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);
}
Related
I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>
I want to pass a javascript variable to my servlet, where I need to use it.
In javascript, the variable count returns the rows of my table and I can show count in the jsp, using $('#counter').html(count); , but I cannot pass count's value to my servlet. I tried document.getElementById("hiddenField").value=count; but it doesn't work.
Javascript
<script>
var count = 3;
$(function() {
$('#counter').html(count);
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
});
document.getElementById("hiddenField").value=count; // ???
</script>
JSP
Count: <span id="counter"></span> <%-- it works --%>
<form method="post" action="newteamsubmit">
...
<input type="hidden" id="hiddenField" name ="countRows" />
<input type="submit" name ="button1" value=" Submit " />
<input type="submit" name = "button1" value=" Cancel " />
</form>
Servlet
String cr = request.getParameter("countRows"); //I' ve tried also to convert it
// to int, but that's not my problem, since I cannot pass the value as a start
I've spent many hours, trying to figure out how I can access a javascript variable in jsp, but I haven't found any solution.
Thanks in advance.
The count is computed each time the add button or the delete button are clicked. But you only set the hidden field value once, when the page is loaded (and its value is thus hard-coded to 3).
You must set it, as you're doing for the #counter element, in your click handlers:
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
Also note that you're repeating exactly the same code in two click handlers here. You should do that only once, for the two buttons:
$('#addButton, #deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
or even, since you're using jQuery:
$('#addButton, #deleteButton').bind('click', function() {
count = $("#dataTable tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
document.getElementById('hiddenField').value is not set because it is outside your document.ready. Put it inside your click handler.
Make sure of 2 things -
There is only one element with id "hiddenField" on your page.
Make sure that the following code
document.getElementById("hiddenField").value=count;
is after in the page.
Just make sure that js sets the hiddenField after the element has been loaded.
3. check for any JS errors using Javascript console.
Rest it looks good
The main issue here is that you are trying to access from the server, a variable that only exists at the client. To access that variable you have to send it from the client to the server using AJAX to trigger some form of API in the backend. REST, SOAP or XML-RPC are common technologies used for this sort of thing. The server side code is used for generating the UI and providing it with data from a database or such. Commonly the UI is generated only once, and then the client calls the server asking for more data in response to user actions, like clicking a button.
Imagine a table filled with information about books: title, author, publish date etc. This table can get quite large, and traditionally this table will be split up over several pages and possibly a dynamic filter. To save bandwidth and increase the user experience by not loading the entire page from scratch you can use AJAX to ask the server for just the relevant data. Doing so the page updates dynamically and smoothly for the user.
In your case, you can use this technique to update the server every time the user clicks the button.
If however you are really just looking to update a hidden field in a form with a value as the user performs actions, and the server wont do anything with it except show it you can just use javascript.
Remember also that the request variable contains the data you post to the server when you submit the form. The servlet will get the data after the client has posted it, which is after the JSP has generated the page. The sequence of the code execution is JSP -> Javascript -> Servlet.
Hope this helps!
You can use this way:
document.forms[0].countRows.value = counter
Hope this will help you
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.
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.
I have a jsp page which should load a popup using ajax. The content of the page is determined by form filled by user.
Something like this:
javascript:
ajax('getPage.action', 'content_id', 'form_id');
foo.jsp:
<div id="content_id"></div>
<form id="form_id">
...
</form>
java/spring:
#RequestMapping("getPage.action")
MyController extends AbstractCommandController {
RealDto dto = (RealDto)command;
...
return new ModelAndView("foo", data);
}
The most difficult part for me is how to send the form data easily as an ajax call. Can I use jQuery here? The form changes dynamically so it would be quite bothersome to list all the fields of the form.
Would it help to use Springs XT (which I never have)?
Yes, you can use serialize to trivially convert the form to send the data.
$("#form1").submit(function() {
$.get("/desiredURL", $("#form1").serialize(), function(response) {
// send response data to a popup
}
}
You can use get or post to send the data.
For the popup I like facebox, but there's loads of choices.
jQuery form plug-in can help you easily transform a regular form to an Ajax one. You only need a single line of code:
$("#myform").ajaxForm(
{beforeSubmit: validate, success: showPopup} );
I don't know about jQuery, but for prototype this is easy:
new Ajax.Request('getPage.action', {
parameters: $('form_id').serialize(true),
onSuccess: someMethod
);
Check out the Prototype API docs.
This page has the same information for jQuery: http://docs.jquery.com/Ajax