Issue with sending multiple ajax requests - jsf

I have a datatable in which the first column contains some links to display the details for each item. I am using f:ajax to send the request to the action listener.
While it does work for the first time (when I click the first link or any link) but after that it stops working and no request is sent to the actionlistener.
<h:commandLink value="#{inquiry.myObject.property}"
actionListener="#{myBean.getDetail}">
<f:param name="someName" value="#{someBean.someName}"/>
<f:ajax
render=":#{p:component('infoDisplay')}
:#{p:component('addFieldSet')} :#{p:component('myDetailsId')}" />
</h:commandLink>
How do I make sure that the request is generated for every link and not just for the first attempt ?
UPDATE---
here is the action listener
public void getDetail(ActionEvent event) {
String xyz=context.getRequestParameterMap().get("someName").toString();
//some task
}
I have set a breakpoint on the first line of this function. This function gets called only once (for the first time).
After the first successful ajax call, I can see the below error in developer tools.
customer?p_p_id=account_WAR_XXX&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_cacheability=cacheLevelPage&p_p_col_id=column-1&p_p_col_count=6&p_p_col_pos=1&_account_WAR_XXX_javax.faces.resource=primefaces.js&_account_WAR_XXX_ln=primefaces&v=4.0:5 Uncaught TypeError: Cannot read property 'source' of undefined

replaced <f:ajax render> with <p:ajax update>. I no longer see the javascript bug on the developer tools and all the functionality seems to work as expected.

Related

logout-method called every time user changes view [duplicate]

This question already has an answer here:
How to call JSF backing bean method only when onclick/oncomplete/on... event occurs and not on page load
(1 answer)
Closed 5 years ago.
<h:outputLink value="/4JVA-157292-war/supinfo/auth/mycar.xhtml">Car</h:outputLink>
<h:outputLink value="Log Out" onclick="${loginController.logout()}" />
As you see, If i click the Car link. I will excute the ${loginController.logout()}, but if i delete the Log out. I will go into the car page.
<h:ouputLink> component is used to render plain a anchor element with its href attribute evaluated as value attribute of <h:outputLink> with the query parameters attached in case the component has <f:param> tags as its children.
<h:ouputLink> is not used to execute server-side actions as you wrongly seemed to expect. You may have confused it with a <h:commandLink> component that is used to trigger a server-side action via a JavaScript call.
If you want to call the action method you must switch to a command comnponent (or its derivative) like <h:commandLink>. Its action attribute should point to the desired action method, like so:
<h:commandLink value="Log out" action="#{loginController.logout}" />
In this way you will be able to execute the bean action method.
Also it is worth noting that since JSF 2.0 there has been an <h:link> component that is useful for handling application-wide navigation. It takes a navigation case outcome in its outcome attribute thus leaving <h:outputLink> component useful for links to external resources.
For more information on the subject read the following answer: When should I use h:outputLink instead of h:commandLink?.
As to the cause of the problem you faced, onclick attribute is rendered as onclick event handler of the generated a element that responds to a click event on the HTML element it is attached to. In case the event is fired a client-side JavaScript code is called (by function call onclick points to or by executing inline code that is contained therein). Do note that onclick runs on the client (in JavaScript context within web browser) while action runs on the server (executes Java code depending on the submit button pressed within web server).
Usage of onclick may be fruitful at least in the following circumstances:
in case it is used in conjunction with a command component it may stop form submission to the server if some client-side requirements are not met (i.e. confirm dialog was shown and cancel button was pressed, or client-side validation failed) as soon as the event will be fired before any consecutive events associated with the element (like form submission):
<h:commandLink value="Delete item" action="#{bean.delete(item)}" onclick="return confirm("Are you sure you want to delete this item?");" ... />
or
<h:commandLink value="Submit data" action="#{bean.action}" onclick="return inputValid();" ... />
with
<script type="text/javascript">
function inputValid() {
var isInputValid = ...;
//decide what's valid or not and set variable to true/false accordingly
return isInputValid;
}
</script>
it may be used to trigger some GUI changes, especially when used in conjunction with non-command components, like in:
<h:button value="Show dialog" onclick="showDialog(); return false;" ... />

onclick for p:outputLabel works on loading/refreshing page but doesn't work when clicking

I have some problems with calling a bean method when clicking on Label.
When page is loading or refreshing click handler function pokus() is called, but when the label is clicked it isn't.
Part of my web page:
<h:form id="pokus">
<p:outputLabel id="pokus2" value="klikni" onclick="#pozadavkyBean.pokus(5)}"/>
</h:form>
and a method in bean:
public void pokus(int i){
System.out.printf("kliknuto sloupec:%d",i);
}
I've also tried it with:
<p:ajax event="click" listener="....
with the same result - method called on loading/refreshing but not when clicking
also tried others events: mousedown, mouseup, .... with same result
using PrimeFaces 5.0
If you will check official document of Primeface regarding Tag outputLabel.You can easily get attribute onclick used for
Client side callback to execute when component is clicked.
But here you are trying to run Managed bean method directly from onclick attribute while onclick used to call JavaScript functions.
As #Mahendran Ayyarsamy Kandiar mentioned and its simple thing outputLabel is not used to call any bean method. Its Just Simply used to show something in the page.In mean time for your requirement you can use CommandButton,CommandLink or some other component but its all depend upon your requirment etc.

How shall technical exceptions be handled when invoked through a listener

I'm using a <h:selectOneMenu> with an valueChangeListener attribute attached to it. The listener invokes some business code (eg. DB query) to load additional data based on the new selected value. I noticed that when an (unexpected) exception happens in that code, a AbortProcessingException wraps the original exception, which is followed by a log but without notifying the user that something went wrong.
Is there a way to notify the user that something unexpected went fatally wrong when invoking a listener ?
I know from Differences between action and actionListener that an action would be more appropriate for such an expression, however I cannot set an action in <h:selectOneMenu>, but only a listener. How shall I change my page so that a "real business action" (one that is allowed to fail) gets invoked when the selected item changes ?
JSF has a concept of FacesMessages. These are rendered with the help of the <h:messages /> tag. What is often done, is to catch any Exceptions and add a javax.faces.application.FacesMessage to the FacesContext, giving the user informations he needs (see also "catch exception in managed bean and show message on screen in jsf2").
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(Severity.INFO, <see details for possible fills>)
);
There are also the way to introduce an own ExceptionHandlerFactory - like mentioned in the article "Global handling of all unchecked / unexpected exceptions in JSF 2"- have you checked this possibility? (see also this answer/comment to BalcusCs article )
As possibility two, you can e.g. use an ajax-request after the selectOneMenu got changed and trigger another Listener with that (it is executed later then the ValueChangedListener and gives the AjaxBehaviorEvent as parameter, what I find to be more helpful on BL - side). Here is some meta-code ...
<h:selectOneMenu ...>
<f:selectItems ... />
<f:ajax render="..." execute="..." listener="..." />
</h:selectOneMenu>
Hope it helps...

Execution order of events when pressing PrimeFaces p:commandButton

I am trying to execute a JSF2 bean method and show a dialog box after completion of the method on click of PrimeFaces <p:commandButton>.
<p:commandButton id="viewButton" value="View"
actionlistener="#{userBean.setResultsForSelectedRow}" ajax="false"
update=":selectedRowValues"
oncomplete="PF('selectedRowValuesDlg').show()">
</p:commandButton>
<p:dialog id="selectedRowValues" widgetVar="selectedRowValuesDlg" dynamic="true">
<h:outputText value="#{userBean.selectedGroupName}" />
</p:dialog>
When I click on the command button, the bean action listener method setResultsForSelectedRow executes properly, but it does not show the dialog box when the method completes. If I remove actionlistener, it shows the dialog box. I do not know what is going wrong.
What is the execution order of events? Is it possible to execute actionlistener and oncomplete simultaneously?
It failed because you used ajax="false". This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete to be never fired (note that all other ajax-related attributes like process, onstart, onsuccess, onerror and update are also never fired).
That it worked when you removed actionListener is also impossible. It should have failed the same way. Perhaps you also removed ajax="false" along it without actually understanding what you were doing. Removing ajax="false" should indeed achieve the desired requirement.
Also is it possible to execute actionlistener and oncomplete simultaneously?
No. The script can only be fired before or after the action listener. You can use onclick to fire the script at the moment of the click. You can use onstart to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:
User clicks button in client
onclick JavaScript code is executed
JavaScript prepares ajax request based on process and current HTML DOM tree
onstart JavaScript code is executed
JavaScript sends ajax request from client to server
JSF retrieves ajax request
JSF processes the request lifecycle on JSF component tree based on process
actionListener JSF backing bean method is executed
action JSF backing bean method is executed
JSF prepares ajax response based on update and current JSF component tree
JSF sends ajax response from server to client
JavaScript retrieves ajax response
if HTTP response status is 200, onsuccess JavaScript code is executed
else if HTTP response status is 500, onerror JavaScript code is executed
JavaScript performs update based on ajax response and current HTML DOM tree
oncomplete JavaScript code is executed
Note that the update is performed after actionListener, so if you were using onclick or onstart to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete instead to show the dialog. Also note that you'd better use action instead of actionListener when you intend to execute a business action.
See also:
Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes
Differences between action and actionListener
I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:
<p:pickList id="formPickList"
value="#{mediaDetail.availableMedia}"
converter="MediaPicklistConverter"
widgetVar="formsPicklistWidget"
var="mediaFiles"
itemLabel="#{mediaFiles.mediaTitle}"
itemValue="#{mediaFiles}" >
<f:facet name="sourceCaption">Available Media</f:facet>
<f:facet name="targetCaption">Chosen Media</f:facet>
</p:pickList>
<p:commandButton id="viewStream_btn"
value="Stream chosen media"
icon="fa fa-download"
ajax="true"
action="#{mediaDetail.prepareStreams}"
update=":streamDialogPanel"
oncomplete="PF('streamingDialog').show()"
styleClass="ui-priority-primary"
style="margin-top:5px" >
<p:ajax process="formPickList" />
</p:commandButton>
The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.
As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.
The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" /> bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.
Happy coding!

PrimeFaces dialog validation errors

What i want to do is like basic row selection example at Primefaces showcase(http://www.primefaces.org/showcase/ui/datatableRowSelectionByColumn.jsf) I want to update my datatable's row. The problem is when i click to update button at datatable, dialogbox appears with validation errors.
Second thing is what is the order of method execution times.(action-update-onclick-f:setPropertyActionListener)
<p:commandButton id="updateButtonId"
action="#{myController.showCompanyEditPanel}"
update=":tabView:companyForm:companyEditPanel"
onclick="companyDialog.show()"
icon="ui-icon-pencil" title="update">
<f:setPropertyActionListener value="#{company}" target="#{myController.selectedCompany}" />
</p:commandButton>
<p:dialog id="editCompanyDialogId" header="CompanyEdit" widgetVar="companyDialog" resizable="false">
<p:panel id="companyEditPanel" >
//some stuff here
</p:panel>
</p:dialog>
You seem to be missing a major point of using a <p:commandButton> here, as well as seem to be mixing client-side and server-side events.
First on <p:commandButton>. This component is designed to POST (partial) form data to the current URL, do business job in action(listener) method and return updated components / perform navigation. You can of course 'attach' JavaScript events to all those attributes.
Second, onclick, oncomplete, and other on... attribute are corresponding to some client-side events. In particular, onclick function is triggered when button was clicked, oncomplete function is called when DOM was updated after the AJAX call, i.e. the elements specified in <p:ajax update="..."> or simply in update="..." attribute of <p:commandButton>.
Third, all action listeners (thus, actionListener attribute, <f:actionListener> tag, <f:setPropertyActionListener> tag) will be executed right in the order they are specified in your tag, see this answer for more elaboration. The last one to be executed is action method, after which response is sent back.

Resources