Updating datatables with ajax - java

I am using spring MVC 4 and dandelion jsp datatables.
I wish to update a column in the table's column (progress percentage) every X seconds without reloading the entire page (probably via ajax).
The update should refer to the controller each X seconds, fetch the requested data and update the column with the results.
I tried to add a simple ajax for external div (not within the table) as a start but it seems to corrupt the table:
<script>
function testAjax() {
$.ajax({
url : 'ajaxtest.html',
success : function(data) {
$('#result').html(data);
}
});
}
<script>
var intervalId = 0;
intervalId = setInterval(testAjax, 6000);
</script>
<body>
<div id="result">123</div>
<div class="container-table">
<datatables:table id="listRecordsModel" data="${listModel}" row="record" cssClass="table table-hover table-striped table-bordered" cellspacing="2" scrollX="120%"
theme="bootstrap2" pageable="true" info="true">
<datatables:column title="Record ID" property="recordId"/>
.
.
.
The controller:
#RequestMapping(value = "/ajaxtest", method = RequestMethod.GET)
public #ResponseBody
String getTime() {
System.out.println("------------------------------------random");////////////////////
return "WORKS!!!";
Is there a simple way doing that?
Thanks,
Mike

I found the problem - the path to the html file was wrong and met with the initial method in the controller so the page loaded from scratch every 6 seconds.
I replaced url : 'ajaxtest.html', with url : '../../ajaxtest.html',.
Thanks anyway!

Related

Thymleaf Spring MVC Button executes Java method

So this is what I have in my HTML file:
<ul>
<th:block th:object="${Post}">
<li class="post" th:each="Post : ${Posts}">
<p th:text ="${Post.getPostText()}"></p>
<button th:onclick = "${Post.upvote()}">Upvote</button>
<button th:onclick = "${Post.downvote()}">Downvote</button>
<p th:text = "${Post.getPostVotes()}"></p>
</li>
</th:block>
</ul>
I want the button to execute a method within the Post class. I'm not sure if I'm using the correct Thymeleaf 'tag'. Right now, when the page loads, it executes the post upvote and downvote methods.
Can anyone help out? I have a feeling I'm using the wrong Thymeleaf Tag.
You need to do a post or get request to invoke those methods. That will only work in JSF, but you can execute the method before de page is rendered as html.
for example this line
<p th:text ="${post.getPostText()}"></p>
will be executed before the page is rendered .
What I do here is to hide a form for both action, two buttons with a name attributes and pass some sort of identifier to know witch entity I'm updating.
In my controller would have two methods that responds to each parameter and return a view or JSON.
So they reason I couldn't do what I wanted to do was because Thymeleaf generates HTML as before the pages loads. It doesn't sit in the HTML waiting to be triggered. I ended up changing the HTML to go to a different URL that would be unique to the post.
<ul>
<th:block th:object="${Post}">
<li class="post" th:each="Post : ${Posts}">
<p th:text ="${Post.getPostText()}"></p>
<a th:href = "#{/post?id={id}&vote=1(id=${Post.getPostId()})}">Upvote</a>
<a th:href = "#{/post?id={id}&vote=0(id=${Post.getPostId()})}">Downvote</a>
<p th:text = "${Post.getPostVotes()}"></p>
</li>
</th:block>
</ul>
And this was the corresponding java code in my controller that would update the object:
#RequestMapping(value = "/post", params = {"id", "vote"})
public String PostVoting(#RequestParam("id") Long id, #RequestParam("vote") int vote)
{
if (currentUser.voteOnPost(id.toString())){
return "redirect:/home";
}
if(vote == 1){
int votes = thePostRepository.findById(id).get().getPostVotes() + 1;
thePostRepository.updateVotes(votes, id);
}
else{
int votes = thePostRepository.findById(id).get().getPostVotes() - 1;
thePostRepository.updateVotes(votes, id);
}
return "redirect:/home";
}
Also, this next part is important if you want to update things like I did:
#Transactional
#Modifying
#Query("UPDATE Post SET votes = :votes WHERE id = :id")
void updateVotes(#Param("votes") int votes, #Param("id") Long id);

Is it possible to get Javascript array in JSP page

I am developing a web application in which I which I have a JavaScript array and I want this array in my JSP page and iterate it save the data in database.
var value = response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// document.getElementById('');
}
}
});
I want this data on my JSP page is it possible. If it is possible, then how?
You can have javascript in jsp but that will always execute on client side. So if you want to save some stuff on trigger of some event inside browser you can do that by making ajax call or form submission. Ajax is preferred way because its faster and better experience for user
But if you have intention of execution of javascript on server side thats not possible
Java script client side script whereas jsp is server side script so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server to store in database.
Client Side:
<script type="text/javascript">
var n = document.getElementById("data");
var f=new Array( "apple", "orange", "mango" );
n.value = f;
</script>
<form action="Your_JSP.jsp" method="POST">
<input type="hidden" id="data" name="data" value="" />
<input type="submit" />
</form>
Server Side:
<%
String val = request.getParameter("data");
String aa[]=val.split(",");
for(String x : aa )
out.println(x);
//now hereyou can use aa array tostore in database or do whatever you want
%>
Try this if you have two different jsp:
first.jsp
<script>
var response = [];
...
var put = function(form) {
form.resp.value = response.join(','); //using comma as separator
};
</script>
<form onsubmit='put(this)' method='next.jsp' method='post'>
<input type='hidden' name='resp' />
<button>Submit</button>
</form>
next.jsp
<%
String[] resp = request.getParameter("resp").split(",");
%>
Response is: ${param.resp} <!-- debugging -->
yes , its possible to do that. you can show array in HTML tag
<!DOCTYPE html>
<html>
<head>
<script>
var value=response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// do here as
document.getElementById("array").innerHTML = sample;
// here array is <p> tag in html and sample is array which will be shown in jsp page.
}
}
</script>
</head>
<body>
<form action="get.jsp" method="POST">
<p id="array" name="array" type="hidden"></p>
<input type="submit" />
</body>
</html>
in get.jsp you will able to get value from array as:
<%
String []array = request.getParameter("array").split(",");
//this String array you can use to store data in DB
%>

Passing servlet values into <div>

on my Java Servlet I have something like this,
request.setAttribute("InfoLog", info);
RequestDispatcher rd = request.getRequestDispatcher("gc.jsp");
and on my jsp page I have a <div>
<div id="box"></div>
Now using Javascript I want to get the servlet values InfoLog and populate that into my div tag, the purpose of this is that I am verifying some conditions in my Javascript function.
How do I get servlet values in Javascript?
In the jsp, you get the value from Servlet as below,
<% String infoLog = (String)request.getAttribute("InfoLog"); %>
and use this infoLog variable in the div as
<div id="box"><%=infoLog%></div>
and in the javascript function particulary in that if condition you can have below code
if(val == "InfoLog")
{
var infoLog = '<%=infoLog%>';
}
Thanks,
Balaji
You can simply get your attribute in your gc.jsp
<div id="box"> <%=request.getAttribute("InfoLog")%> </div>
Then, if you want to get this value in javascript you can write -
var val = document.getElementById("box").innerHTML;

Wicket datatable change font or css of cell after onchange

In my application I have a defaultDataTable, with a clickable column and a search field to filter the table. The filter filters the content of the datatable after a character is inserted into the input field. My goal is to underline (or other css) the parts of the text in the fields that apply to the input of the user.
Example: The characters 'a' and 'b' of the string 'abc' should be underlined if the user enters 'ab'. With Javascript I can add some styling, but my function does some strange things with the datatable. It deletes everything inside the table tags en puts the new html there. All the other information is gone. What am I doing wrong?
<script>
$('.searchField').keyup(function(){
var page = $('.datatable');
alert(page.text());
var pageText = page.text().replace("<span>","").replace("</span>");
alert(pageText);
var searchedText = $('#searchField').val();
var theRegEx = new RegExp("("+searchedText+")", "igm");
var newHtml = pageText.replace(theRegEx ,"<b>$1</b>");
alert(newHtml);
page.html(newHtml);
});
</script>
New table:
<table id="ID" class="datatable" wicket:id="ID">
Col1 Col2 123
<b>MATCHEDCHAR</b>
TEXT
<b>MATCHEDCHAR</b>
TEXT
</table>
Old table (collapsed body en head):
<table id="ID" class="datatable" wicketsource="URL.java" wicket:id="ID">
<thead wicketsource="org.apache.wicket.extensions.markup.html.repeater.data.table:DataTable.java:181" wicket:id="topToolbars">
<tbody wicketsource="org.apache.wicket.extensions.markup.html.repeater.data.table:DataTable.java:207" wicket:id="body">
<tr class="even" wicketsource="org.apache.wicket.extensions.markup.html.repeater.data.table:DefaultDataTable.java:71" wicket:id="rows">
</tbody>
</table>
I think you have a handler on searchField which perform table refresh.
So all you need is just to subcribe on complete ajax event.
Wicket.Event.subscribe('/ajax/call/complete', function(jqEvent, attributes, jqXHR, errorThrown, textStatus) {
// call code that highlight the text
});
You can put this subscription method in the page(in a script tag).
If you want to link js call to a specific behavior say OnChangeAjaxBehavior, then you need to call target.appendJavaScript:
new OnChangeAjaxBehavior(){
#Override
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavaScript("<call highlight function here>");
}
};
Try this jquery highlight plugin.
More about ajax global call listeners here.
I've made a simple demo so you can check it.

How can i do DropDownBox IndexChanged Event in Jsp page?

I m adding DropDown in jsp page.
and m trying to redirect a page exact after index change without any button click.
How can i add it to jsp page?
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(function(){
$('com').bind('change', function () {
var value = $(this).val();
if(value==1) window.location = "servlet1?id=1";
if(value==2)window.location = "servlet1?id=2";
return false;
});
});
</script>
<body>
<select id="com">
<option></option>
<option value="1">Link1</option>
<option value="2">Link2</option>
</select></body>
Not working, is anything missing , plz
When i change index then i want to redirect to corresponding link/page.
Using jQuery you could do it as follows,
$(function(){
// bind change event to select
$('#ID_OF_select_ITEM').bind('change', function () {
var value = $(this).val(); // get selected value
window.location = someURL; // redirect based on the value
return false;
});
});
Just use '#com' instead of 'com' probably it will work
if still not working then let us know we have alternative for this task

Categories

Resources