How to do double-click prevention in JSF - jsf

We have a few search pages that run against a lot of data and take a while to complete. When a user clicks on the search button, we'd like to not allow them to submit the search result a second time.
Is there a best practice for doing "double-click" detection/prevention in JSF?
The PrimeFaces component seems like it can do what we want as it will disable the UI for a period of time between when the search button is clicked and when the search completes, but is there a more generic strategy we can use (perhaps something that isnt reliant on PrimeFaces)? Ideally, any click of the button will either be disabled or disregarded until the search completes. We dont necessarily need to disable the entire UI (as blockUI allows you to do).

If you're using solely ajax requests, you could use jsf.ajax.addOnEvent handler of the JSF JavaScript API for this. The below example will apply on all buttons of type="submit".
function handleDisableButton(data) {
if (data.source.type != "submit") {
return;
}
switch (data.status) {
case "begin":
data.source.disabled = true;
break;
case "complete":
data.source.disabled = false;
break;
}
}
jsf.ajax.addOnEvent(handleDisableButton);
Alternatively, if you need this on specific buttons only, use the onevent attribute of <f:ajax>.
<h:commandButton ...>
<f:ajax ... onevent="handleDisableButton" />
</h:commandButton>
If you also need to apply this on synchronous requests, then you need to take into account that when you disable a button during onclick, then the button's name=value pair won't be sent as request parameter and hence JSF won't be able to identify the action and invoke it. You should thus only disable it after the POST request has been sent by the browser. There is no DOM event handler for this, you'd need to use the setTimeout() hack which disables the button ~50ms after click.
<h:commandButton ... onclick="setTimeout('document.getElementById(\'' + this.id + '\').disabled=true;', 50);" />
This is only rather brittle. It might be too short on slow clients. You'd need to increase the timeout or head to another solution.
That said, keep in mind that this only prevents double submits when submitting by a web page. This does not prevent double submits by programmatic HTTP clients like URLConnection, Apache HttpClient, Jsoup, etc. If you want to enforce uniqueness in the data model, then you should not be preventing double submits, but preventing double inserts. This can in SQL easily be achieved by putting an UNIQUE constraint on the column(s) of interest.
See also:
Pure Java/JSF implementation for double submit prevention
How to handle multiple submits before response is rendered?

You can use 'onclick' and 'oncomplete' listeners. When user click on button - disable it. When action completed - enable.
<p:commandButton id="saveBtn"
onclick="$('#saveBtn').attr('disabled',true);"
oncomplete="$('#saveBtn').attr('disabled',false);"
actionListener="#{myBean.save}" />

i came upon this question, having the same problem. The solution did not work for me - after a brief look at primefaces.js i guess they do not use jsf.ajax there anymore.
so i had to work something out myself and here is my solution, for people who also can not use the one in the answer by BalusC:
// we override the default send function of
// primeFaces here, so we can disable a button after a click
// and enable it again after
var primeFacesOriginalSendFunction = PrimeFaces.ajax.AjaxUtils.send;
PrimeFaces.ajax.AjaxUtils.send = function(cfg){
var callSource = '';
// if not string, the caller is a process - in this case we do not interfere
if(typeof(cfg.source) == 'string') {
callSource = jQuery('#' + cfg.source);
callSource.attr('disabled', 'disabled');
}
// in each case call original send
primeFacesOriginalSendFunction(cfg);
// if we disabled the button - enable it again
if(callSource != '') {
callSource.attr('disabled', 'enabled');
}
};

None of alternatives above has worked for me (I've really tried each one of them). My form was always sent twice when user double-clicked the login button. I'm working with JSF (Mojarra 2.1.6) on Glassfish 3.1.2.
Consider that it was a non-AJAX login page.
So here's the way I solved it:
define a global JavaScript var to control submition in the page header or anywhere outside your form:
var submitting = false;
set it to true when submit h:form onsubmit event is fired:
<h:form onsubmit="submitting = true">
Check the var's value on h:commandLink's click event:
<h:commandLink ... onclick="if(submitting){return false}">
This is just another simple alternative and it was tested in Chrome [Version 47.0.2526.106 (64-bit)], Mozilla Firefox (37.0.2) and Internet Explorer 11. I hope it helps someone.

For me works this way:
<h:commandLink ... onclick="jQuery(this).addClass('ui-state-disabled')">

PrimeFaces 12 and up
From PrimeFaces 12, p:commandButtons are disabled by default when they trigger an Ajax request. The button is enabled again when the Ajax request is finished.
To disable this default behavior, use disableOnAjax="false".
See a demo at: https://www.primefaces.org/showcase/ui/button/commandButton.xhtml
PrimeFaces 11 and lower
The approach by BalusC is great, but if you are using PrimeFaces you'll run into styling issues. Because some classes are not toggled, the button will not look disabled.
If you are looking for a solution which takes care of styling as well, you can replace the CommandButtonRenderer with one that disables the button on click using the button's widget to disable and enable it.
PrimeFaces Extensions 8 or up contains such a renderer. You can add this to your faces-config.xml like:
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.CommandButtonRenderer</renderer-type>
<renderer-class>org.primefaces.extensions.renderer.CommandButtonSingleClickRenderer</renderer-class>
</renderer>
</render-kit>
You can see it in action in the showcase.
If you cannot or don't want to use PFE, you can add the render class to your project by getting it from:
https://github.com/primefaces-extensions/primefaces-extensions/blob/master/core/src/main/java/org/primefaces/extensions/renderer/CommandButtonSingleClickRenderer.java
Note: this still requires you to add the renderer to your faces-config.xml.
See also
How to use resolveWidgetVar before PrimeFaces 8?

very useful solution jsf-primefaces, used with facelets template spreads to other pages consumers
<f:view>
<Script language="javascript">
function checkKeyCode(evt)
{
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if(event.keyCode==116)
{
evt.keyCode=0;
return false
}
}
document.onkeydown=checkKeyCode;
function handleDisableButton(data) {
if (data.source.type != "submit") {
return;
}
switch (data.status) {
case "begin":
data.source.disabled = true;
break;
case "complete":
data.source.disabled = false;
break;
}
}
jsf.ajax.addOnEvent(handleDisableButton);
</Script>
</f:view>
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="./resources/css/default.css" rel="stylesheet" type="text/css" />
<link href="./resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
<title>infoColegios - Bienvenido al Sistema de Administracion</title>
</h:head>
<h:body onload="#{login.validaDatos(e)}">
<p:layout fullPage="true">
<p:layoutUnit position="north" size="120" resizable="false" closable="false" collapsible="false">
<p:graphicImage value="./resources/images/descarga.jpg" title="imagen"/>
<h:outputText value="InfoColegios - Bienvenido al Sistema de Administracion" style="font-size: large; color: #045491; font-weight: bold"></h:outputText>
</p:layoutUnit>
<p:layoutUnit position="west" size="175" header="Nuestra InstituciĆ³n" collapsible="true" effect="drop" effectSpeed="">
<p:menu>
<p:submenu>
<p:menuitem value="Quienes Somos" url="http://www.primefaces.org/showcase-labs/ui/home.jsf" />
</p:submenu>
</p:menu>
</p:layoutUnit>
<p:layoutUnit position="center">
<ui:insert name="content">Content</ui:insert>
</p:layoutUnit>
</p:layout>
</h:body>

Did a simple work with hide and show, works well with element having input type submit Jquery
$(":submit").click(function (event) {
// add exception to class skipDisable
if (!$(this).hasClass("skipDisable")) {
$(this).hide();
$(this).after("<input type='submit' value='"+$(this).val()+"' disabled='disabled'/>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<form>
<input type="submit" value="hello">
</form>

I addressed this issue by simply hiding the button after clicking it:
<p:commandButton... onclick="jQuery(this).css('visibility','hidden')" />

Related

How to refresh page after f:actionlistener event

Working with JSF, I have a <ux:confirm> tag, which has a confirm button. When clicked it triggers a actionListenerEvent. The page and the objects in the faces context are updated, however I have a bootstrap accordion which is not updated. A solution would be refreshing the page, which is my question.
<ux:confirm
ok="#{message.get('Label.Sim')}"
ajax="true"
render="form-consulta"
cancel="#{message.get('Label.Nao')}"
title="#{message.get('Label.Excluir')}"
message="#{message.get('Msg.DesejaExcluirRegistro')}"
>
<f:actionListener
for="onOkClick"
binding="#{bean.excluir()}"
/>
</ux:confirm>
Ok, solved by just adding a JavaScript function on the ajax event and also calling somewhat a template method using javascript.
<f:ajax
render="#{cc.attrs.render}"
disabled="#{not cc.attrs.ajax}"
onevent="onEventConfirm"
/>
function onEventConfirm(data) {
App.ajax.onEvent(App.view.block, null, null, App.view.unblock);
var status = data.status;
switch (status) {
case "complete":
if(shouldRefreshAfterConfirmation)
this.location.reload();
break;
}
}

Primefaces: Input Text / Overlay panel / Retain focus

We have a p:inputText element that should display an overlay panel for various options. (Its a global search, so you can tick categories to search in)
Users usually click in the textbox, start typing and THEN look at the screen again
The Problem is: As soon as the overlay panel is shown, the textbox looses its focus.
<p:inputText id="searchItem"></p:inputText>
<p:overlayPanel id="gsOverlay" for="searchItem" my="left top"
at="left bottom" dynamic="true"
onShow="resizeGSOverlay();">
So i tried to fix this, by immediately focusing back on the "search" inputtext using
<p:overlayPanel id="gsOverlay" for="searchItem" my="left top"
at="left bottom" dynamic="true"
onShow="PrimeFaces.focus('globalSearchForm:searchItem'); resizeGSOverlay();">
However, there is a split second, where the inputfield lost focus, leading to searches missing the first charater.
Can i display the overlay panel, without having the inputtext loosing its focus? (Each component inside the overlay panel will focus back after clicking, that's fast enough - just the initial focus-back is to slow)
Just found the "holy grail":
Default for the overlayPanel is:
PrimeFaces.widget.OverlayPanel.prototype.applyFocus = function(){
this.jq.find(':not(:submit):not(:button):input:visible:enabled:first').focus();
}
so, I just put the following javascript AFTER including the primefaces resources, which will then override the default implementation:
<script type="text/javascript">
PrimeFaces.widget.OverlayPanel.prototype.applyFocus = function() {
if (this.id == "globalSearchForm:gsOverlay")
return;
else
this.jq.find(':not(:submit):not(:button):input:visible:enabled:first').focus();
}
</script>
So - No focus for any element within the overlay panel in question once it becomes visible. Works like a charm.
Update:
using the Proxy Pattern (http://api.jquery.com/Types/#Proxy_Pattern) seems a more reliable solution, as it avoids the need to duplicate the content of the original implementation, which might be different in one of the next Primefaces releases:
<script type="text/javascript">
(function() {
var proxied = PrimeFaces.widget.OverlayPanel.prototype.applyFocus;
PrimeFaces.widget.OverlayPanel.prototype.applyFocus = function(){
if (this.id == "globalSearchForm:gsOverlay")
return;
return proxied.apply(this, arguments);
};
})();
</script>

How to count the number of times a h:outputLink was clicked?

I have a PrimeFaces page with following code:
<pm:content id="content">
<p:dataList value="#{likeditems.likedItems}" var="item" pt:data-inset="true" paginator="true" rows="5">
<f:facet name="header">
Products you liked in the past
</f:facet>
<h:outputLink value="#{item.url}" target="_new">
<p:graphicImage name="http://example.com/my-product-mobile/f/op/img/underConstructionImage.jpg" />
<h2>#{item.title}</h2>
<p>Approx. #{item.price} (for most up-to-date price, click on this row and view the vendor's page)</p>
</h:outputLink>
<f:facet name="footer">
Products you liked in the past
</f:facet>
</p:dataList>
</pm:content>
When the user clicks on the h:outputLink, I want 2 things to happen:
A new page with URL item.url is opened in the browser.
Method likeditems.itemLinkClicked(item) is invoked (in that method I update the number of times a particular link was clicked).
First thing is already working (target="_new").
How can I implement the second one (method call for updating the number of times the link was clicked) without the first ceasing to work?
First thing is already working (target="_new").
The target should actually be _blank.
How can I implement the second one (method call for updating the number of times the link was clicked) without the first ceasing to work?
The simplest (naive) JSF-ish way would be triggering a <p:remoteCommand> on click.
<h:outputLink value="#{item.url}" target="_blank" onclick="count_#{item.id}()">
...
</h:outputLink>
<p:remoteCommand name="count_#{item.id}" action="#{likeditems.itemLinkClicked(item)}" />
But this generates lot of duplicate JS code which is not very effective. You could put it outside the data list and fiddle with function arguments. But this still won't work when the enduser rightclicks and chooses a context menu item (open in new tab, new window, new incognito window, save as, copy address, etc). This also won't work when the enduser middleclicks (default browser behavior of middleclick is "open in a new window").
At ZEEF we're using a script which changes the <a href> on click, middleclick or rightclick to an URL which invokes a servlet which updates the count and then does a window.open() on the given URL.
Given a
<h:outputLink value="#{item.url}" styleClass="tracked" target="_blank">
the relevant script should basically look like this:
// Normal click.
$(document).on("click", "a.tracked", function(event) {
var $link = $(this);
updateTrackedLink($link);
var trackingURL = $link.attr("href");
$link.attr("href", $link.data("href"));
$link.removeData("href");
window.open(trackingURL);
event.preventDefault();
});
// Middle click.
$(document).on("mouseup", "a.tracked", function(event) {
if (event.which == 2) {
updateTrackedLink($(this));
}
});
// Right click.
$(document).on("contextmenu", "a.tracked", function(event) {
updateTrackedLink($(this));
});
// Update link href to one of click count servlet, if necessary.
function updateTrackedLink($link) {
if ($link.data("href") == null) {
var url = $link.attr("href");
$link.data("href", url);
$link.attr("href", "/click?url=" + encodeURIComponent(url));
}
}
and the click servlet should look like this (request parameter validation omitted for brevity):
#WebServlet("/click")
public class ClickServlet extends HttpServlet {
#EJB
private ClickService clickService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getParameter("url");
clickService.incrementClickCount(url);
response.sendRedirect(url);
}
}
Note that this way the target="_blank" isn't necessary. It would only be used by users who have JavaScript disabled. But then many more other things on the website wouldn't work anyway, including the above JS tracking. It this is also really your concern, then you'd better just put that click servlet URL directly in <h:outputLink value>.

Javascript calculator in JSF view calling server side

I need to make a calculator in a jsf view using only client-side part. No data can be passed to server-side.
I have the view splitted in a couple of <h:form> with calculator in the middle:
<h:form id="customer_form">
// view here working nice
</h:form>
<h:panelGroup layout="block" styleClass="ui-grid-col-2 offset-boxes" >
<p:panel id="calculator" header="Calculadora" styleClass="half-screen-height calculator-table">
<h:inputText id="result" widgetVar="result" styleClass="result-text"/>
<p:button value="X" widgetVar="X" ajax="false" onclick="calculate('x')" styleClass="right"></p:button>
// more calculator buttons
</p:panel>
</h:panelGroup>
<h:form id="consumption_form">
// view here working nice
</h:form>
Until here all is ok, but when I try to manage calculator with javascript:
<script type="text/javascript">
function calculate(sel){
if (sel == "x") {
document.getElementById("result").value = "";
} else {
var input = document.getElementById("result").value;
document.getElementById("result").setAttribute("value", input + sel);
}
}
</script>
Each time i change result value, server-side is called and value is reset to original value.
EDIT according to PrimeFaces documentation of p:button::onclick event
Client side callback to execute when button is clicked.
Either <h:button> tag is acting like this, so I guess problem is the way JSF or PrimeFaces are handling the javascript event...
I also tried to call and set input value by jquery with $("result").value but the result i get is a function(b7) not the value itself.
What am I doing wrong?
Thanks! ;)
J
you got to make sure you're JS code will not try to submit the form, so that will trigger a server side call, for that I suggest you return false and try using event.preventDefault() on your HTML buttons onclick calls, so you will avoid bubbling up the event to any listeners.

Programmatically control which components should be ajax-updated

I have a complex form where the user fills a few fields, and has two options: generate a license file or save the changes. If the user clicks on the generate license file button without saving the changes, I render a small component with an error message asking him to save before generating the license.
To display the component with a warning message, I want to use ajax to avoid rendering the whole page just to render the warning component. Of course, if the changes were saved, then the warning message is not required and I redirect the user to another page.
I have a change listener on the changeable fields to detect when a change has been made. What I don't know is the conditional execution. The "render with ajax if unsaved OR redirect if saved" part. Here's the logic
if(saved){
redirect();
}else{
ajax.renderWarning()
}
--EDIT--
I'm going to add more info because I realized I'm leaving things too open ended.
Here's one example of an updateable field.
<h:inputText name="computername3" value="#{agreement.licenseServerBeans[2].computerId}" valueChangeListener="#{agreement.fieldChange}">
<rich:placeholder value="Add Computer ID"/>
</h:inputText>
The fieldChange() bean method
public void fieldChange(ValueChangeEvent event) {
change = true; //change is a boolean, obviously :P
}
Here's the generate license button jsf
<h:commandLink action="#{agreement.generateLicenseFile}">
<span class="pnx-btn-txt">
<h:outputText value="Generate License File" escape="false" />
</span>
</h:commandLink>
Here's the generateLicenseFile() method
public String generateLicenseFile(){
....//lots of logic stuff
return "/licenseGenerated.xhtml?faces-redirect=true";
}
Use PartialViewContext#getRenderIds() to get a mutable collection of client IDs which should be updated on the current ajax request (it's exactly the same as you'd specify in <f:ajax render>, but then in form of absolute client IDs without the : prefix):
if (saved) {
return "/licenseGenerated.xhtml?faces-redirect=true";
}
else {
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("formId:messageId");
return null;
}
Returning null causes it to redisplay the same view. You can even add it as a global faces message and let the ajax command reference the <h:messages> in the render.
if (saved) {
return "/licenseGenerated.xhtml?faces-redirect=true";
}
else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(...));
return null;
}
with
<h:messages id="messages" globalOnly="true" />
...
<f:ajax render="messages" />

Resources