Struts 2 jQuery plugin isSubscribe not working - java

The struts 2 jQuery plugin has a built in publish/subscribe framework.
If you define your own publish and subscribe event (for example on a grid) the subscribed function will be called every time the event is published. For details please see (Struts 2 jQuery Subscribe is called more than once)
To prevent this, there is a isSubscribed method which can be used.
For a grid as:
<sjg:grid id="gridtable"
onBeforeTopics="before_grid_load" >
The JS will be:
$.subscribe('before_grid_load', function(event, data) {
if ( $('#gridtable').isSubscribed('before_grid_load') ){
return ;
}
//go on with function
}
The problem is that the $('#gridtable').isSubscribed('before_grid_load') returns false every time!

The function isSubscribed is applied on the element $('#gridtable') but subscribed to the $(document). I have tested with the last element and it didn't work to me. But tried with the first element and it worked.
Script:
<head>
<link href="<s:url value="/css/template_styles.css"/>" type="text/css" rel="stylesheet">
<sj:head />
<title>jQuery Grid</title>
<script type="text/javascript">
$(document).ready(function(){
console.log("Before subscribe");
$("#gridtable").subscribe("beforeTopic", function(topic, data) {
console.log('Topic: '+data, topic);
if ( $("#gridtable").isSubscribed("beforeTopic") ){
console.log('Subscribed: '+data, topic);
return;
}
//go on with function
console.log('Not subscribed: '+data, topic);
});
console.log("After subscribe");
});
</script>
</head>
For grid:
<sjg:grid id="gridtable"
onBeforeTopics="beforeTopic" >

Check your lib to your jsp
<%# taglib prefix="sjg" uri="/struts-jquery-grid-tags"%>
Enable jQuery Grid Plugin in your Head Tag
<sj:head jqueryui="true" jquerytheme="redmond" />

Related

Struts2 - Set redirection to false

I am using Struts2 framework (with annotations) and need help in redirection.
Step 1: The action class extends ActionSupport, in execute method add action message. On success of action, location is set to a JSP - common_popup.jsp.
Step 2: In JSP check for hasActionMessages() and sets a dialog with action messages.
ISSUE: a. On action success due to redirection the action messages set are lost.
b. Due to redirection the common_popup.jsp is opening up in a new URL.
Is there a way to set redirection to FALSE ? Such that I retain the page which submitted request to action class and common_popup.jsp appears on top of same page as a popup dialog.
ACTION Class:
public class Settings extends ActionSupport {
#Action(value="settings",
results = { #Result (name="success", location="common_popup.jsp"),
#Result (name="failure", location="${actionUrl}")
})
#Override
public String execute()
{
try {
addActionMessage(" ITS SETTINGS TIME !! ");
}
catch (Exception exp )
{
addActionError(" Failed to update the data base configuration. Please retry. ");
this.actionUrl = "main.jsp?settings=true";
return "failure";
}
return "success";
}
}
JSP Code - common_popup.jsp:
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheets/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="stylesheets/loader.css">
<script src="scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.10.4.js" type="text/javascript"></script>
<script src="scripts/loader.js" type="text/javascript"></script>
</head>
<body>
<s:if test="hasActionMessages()">
<div id="actionMessage" class="ui-dialog" style="display:none" >
<s:actionerror/>
</div>
<script>
$( "#actionMessage" ).css("display","");
$( "#actionMessage" ).dialog();
</script>
</s:if>
</body>
</html>
The result results = { #Result (name="success", location="common_popup.jsp") is forwarding a servlet dispatcher to the URL built from the result location.
This is also known a default dispatcher result type. So, in you code you are not redirect, but dispatch or forward the JSP page specified by the location attribute.
So, nothing in your code that has shown is redirecting. If it does and you want to save action messages between actions (you should not redirect to the JSP) you can use messageStore interceptor.
Find the examples of this interceptor on the linked page or read my answers to find more detailed explanation with examples.

Auto Refresh Portlet Liferay 6.0(Periodically refresh)

I want To create Portlet For Monitoring Something, so it need like automatically refresh portlet page every interval of time, how i can achieve this? I've been trying with normal method like using Javascript but its didn't work... Thanks, please give me example :(
any help would be really appreciate
i'm trying using normal code for jsp but it's cant run
<%# page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh Header Example</title>
</head>
<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%
// Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Crrent Time: " + CT + "\n");
%>
</center>
</body>
</html>
Regards
Danial
I'm Managed to solve this problem using this code
<%#page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
<%#page import="java.util.Date"%>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
$.post('<portlet:renderURL windowState="<%= LiferayWindowState.EXCLUSIVE.toString() %>"></portlet:renderURL>', function(data){
$("#myportlet").html(data);
})
}
timedRefresh(5000);
// -->
</script>
<div id="myportlet"><%= new Date() %></div>
Thanks to #boky who give me the main idea how to solve this problem :)
Regards
Danial
If you want update your portlet at regular interval, you can make use of serveResource method.
Make an ajax call to serveResource method and you can set setTimeout on this ajax call. Following is the sample code snippet -
function <portlet:namespace />get_updated_data() {
var f = jQuery.ajax({
type: "POST",
url: '<<resourceUrl>>',
data: {"name" : "val"},
dataType: 'json',
async: false,
}).success(function(data){
// success code here
}).complete(function(){
setTimeout(function(){<portlet:namespace />get_updated_data();}, 5000);
});
}
Setting the Refresh header will in -- best case scenario -- refresh the whole page (that's what it's meant to do) and not just your portlet.
How you set up this refresh depends on your underlying technology for writing the portlet. Basically you want to do an AJAX request to your page to fetch the new data and redisplay it, as #harishkrsingla suggested.
If your code is pure JSP, you would set up two pages:
- one for displaying the portlet
- the other that's rendering the content
Your portlet page would then look something like this (really writting this off the top of my head, check documentation online):
<div id="portlet">
<jsp:include file="data.jsp" />
</div>
<script type="text/javascript">
// assuming jquery
var load;
load = function() {
$('#portlet').load('<portlet:namespace />/data.jsp', function() {
window.setTimeout(load, 1000);
});
}
load();
</script>
Also check out the working demo on JSFiddle: http://jsfiddle.net/z9az9/1/
Of course, this is just the basic idea. You should really include some error handling etc.

getting an immediate redirect. Why is this so?

I am trying to redirect the user from one jsp page to another jsp page after making him wait for 10 seconds or 10000 milliseconds. But there is a redirect as soon as the page is opened in the browser. Why is this is so ? Is there anything wrong in the following code ? I am calling the redirectFunction which does the redirect.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP - 1</title>
<script>
function redirectFunction() {
<% response.sendRedirect("jsp-2.jsp"); %>
}
</script>
</head>
<body>
<h1>
Wait while you are redirected...
</h1>
<script type="text/javascript">
setTimeout(redirectFunc,10000); // wait for 10 seconds,then call redirectFunc
</script>
</body>
You sends redirect exactly from server that`s why it fired immediatelly.
If you want to fire redirect after 10 seconds than you need to change your code:
function redirectFunction() {
window.location.href = "jsp-2.jsp"
}
and setTimeout(redirectFunction,10000);
Actually when you call <% response.sendRedirect("jsp-2.jsp"); %> Java server sets http code 302 to your http response, and header Location: jsp-2.jsp
And browser redirects to page specified in Location header immediately.
Hope it helps.
the code in scriptlet is executed on the server, it is not javascript. use this
function redirectFunction() {
window.location.href = "jsp-2.jsp";
}
Assuming you're using HttpServletResponse, what's happening is that you're sending the HTTP location header with a status code 302. This happens when the page is requested, not during client-side execution of the JavaScript.
If you want it to be during JavaScript execution you need to assign the URL you want to window.location.
window.location = "http://google.com";
for example
This is because
<script>
function redirectFunction() {
<% response.sendRedirect("jsp-2.jsp"); %>
}
</script>
is translated and executed as
out.print(" <script> function redirectFunction() {");
response.sendRedirect("jsp-2.jsp");
out.print("</script>");
The call sendRedirect is executed on the server side, while preparing your page, and it's performing the redirect. You can do the sleep and the redirect in javascript only, using window.location.

Jquery Autocomplete token input does'nt work in safari and chrome

Autocomplete token input box works properly in IE and Firefox but it doesn't work in safari and crome.
this is a part of code
<script type="text/javascript" src="<%=path%>/js/jquery-1.4.4.min.js"></script>
//for auto complete
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jqueryAutocomplete/jquery.autocomplete.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jqueryAutocomplete/jquery.ajaxQueue.js"></script>
<link type="text/css" media="screen" rel="stylesheet" href="<%=request.getContextPath()%>/css/jqueryAutocomplete/jquery.autocomplete.css" />
$j(document).ready(function(){
$j("#id_CBRERegion").tokenInput(path + "fetchAutoCompleteResult.do?method=regionList", {
theme: "facebook",
queryParam: "search",
minChars: 1,
preventDuplicates: true,
hintText:"CBRE Region",
prePopulate: selRegCode
});
$j('#id_CBRERegion').prev().find("input").blur();
registerAutoEvent('id_CBRERegion','id_CBRERegion_Temp');
if(document.getElementById('id_CBRERegion').value != "") {
$j('#id_CBRERegion_Temp').hide();
} else if(document.getElementById('id_CBRERegion').value == "") {
$j('#id_CBRERegion_Temp').next().hide();
}
});
Please suggest..
I just visited http://jqueryui.com/demos/autocomplete/ in Chrome and Safari and it works.
Many factors could be causing the problem, from css to data.
Best way to resolve and learn the function.
start from a simple example off the site
Add in your bits slowly until you see it fail.

Accessing selected node of richfaces tree from Javascript

This should be a very simple question. I have a richfaces tree that is rendered using JSF. When the user clicks on a node I want a javascript function to run. Nothing more nothing less. No redirects, no re-submit, no-rerender, no Ajax. Just plain old Javascript.
I have seen the onselected attribute of the tree and it indeed fires a Javascript method. But of course I want to know which node was clicked.
Here is what I have so far
<head>
<script type="text/javascript">
function documentClicked(nodeRef)
{
alert("Node is "+nodeRef);
}
</script>
</head>
<rich:tree switchType="client" value="#{ajaxDocumentTree.rootNode}"
var="document" onselected="documentClicked()" >
<rich:treeNode iconLeaf="../images/tree/doc.gif"
icon="../images/tree/doc.gif">
<h:outputText value="#{document.friendlyName}" />
</rich:treeNode>
But this does not work because nodeRef is undefined. I expected that the first argument of the callback would be the selected node but this is not the case.
So the question is this:
How do I fire a Javascript function with the selected node from a richfaces tree?
The answer is that the javascript code should be on the node level instead of the tree level.
<head>
<script type="text/javascript">
function documentClicked(nodeRef)
{
alert("Node id is "+nodeRef);
}
</script>
</head>
<rich:tree switchType="client" value="#{ajaxDocumentTree.rootNode}"
var="document" >
<rich:treeNode onclick="documentClicked('#{document.id}')">
<h:outputText value="#{document.friendlyName}" />
</rich:treeNode>
I have little experience with JSF, but shouldn't this (in the scope of your event handler) be referring to the selected node, as it usually does in JavaScript?
Change your function to this and try it out:
function documentClicked()
{
alert("Node is " + this);
}
EDIT: the above was obviously not correct. As per my comment below, change your JSF to
<rich:tree switchType="client" value="#{ajaxDocumentTree.rootNode}"
var="document" onselected="documentClicked(this)" >

Categories