I have a delete button which I use to delete table rows:
//Dialog
function deletedialog(a){
$("<div />", {
text: a
}).dialog({
width: 600,
buttons: {
"Ok": function() {
$("#form\\:deleterow").click();
// $('input[id$="deleterow"]').click();
$(this).dialog("close");
},
"Cancel": function(event) {
$(this).dialog("close");
event.preventDefault();
}
}
});
}
<h:commandButton id="deleterow" value="HiddenDelete" action="#{SessionsController.deleteSelectedIDs}" style="display:none">
<f:ajax render="#form"></f:ajax>
</h:commandButton>
<!-- the delete button -->
<h:commandButton value="Delete">
<f:ajax execute="#form" onevent="deletedialog('Do you want to delete the selected rows?')"></f:ajax>
</h:commandButton>
I want when I press the delete button during the execution time of the Java delete method to disable it. I also want to change the visual name if the button from "Delete" to "Processing" like the buttons in Glassfish. This case is little more complicated because I use hidden button. How I can do this?
Post Update
<!-- the delete button -->
<h:button value="Delete" onclick="deletedialog('Do you want to delete the selected rows?'); return false;" />
Post Update 2
I edited the code this way:
//Dialog
function deletedialog(button, a){
button.value = "Processing...";
button.disabled = true;
$("<div />", {
text: a
}).dialog({
width: 600,
buttons: {
"Ok": function() {
$("#form\\:deleterow").click();
// $('input[id$="deleterow"]').click();
$(this).dialog("close");
button.value = "Delete";
button.disabled = false;
},
"Cancel": function(event) {
$(this).dialog("close");
event.preventDefault();
button.value = "Delete";
button.disabled = false;
}
}
});
}
<!-- hidden button -->
<h:commandButton id="deleterow" value="HiddenDelete" action="#{SessionsController.deleteSelectedIDs}" style="display:none">
<f:ajax render="#form"></f:ajax>
</h:commandButton>
<!-- the delete button -->
<h:button value="Delete" onclick="deletedialog(this, 'Do you want to delete the selected rows?'); return false;" />
Well the button works. The problem is that when I click delete button the button is disabled only for the time when the dialog is opened. I need to keep the button disabled when I perform the background database operation.
This is not the proper usage of the onevent attribute. The onevent attribute should point to a special function which is invoked on every ajax event (begin, complete and success) in which JSF will supply the data argument itself. E.g.
<f:ajax ... onevent="functionname" />
with
function functionname(data) {
var ajaxStatus = data.status; // Can be 'begin', 'complete' and 'success'.
switch (ajaxStatus) {
case 'begin': // This is called right before ajax request is been sent.
// ...
break;
case 'complete': // This is called right after ajax response is received.
// ...
break;
case 'success': // This is called when ajax response is successfully processed.
// ...
break;
}
}
This is useful to for example show an ajax progress/status image, or to disable/enable the submit button, etc. It is not possible to control or block ajax requests in there. It's merely a listener function.
But you want to invoke your confirm dialog before the ajax request is ever sent. You need to hook on the onclick attrubute of the button instead and let the function return true or false depending on the outcome. In simplest form, with the builtin JavaScript confirm() function, it should look like this:
<h:commandButton value="Delete" onclick="return confirm('Are you sure?')">
<f:ajax execute="#form" />
</h:commandButton>
When using the jQuery confirm dialog function which in turn invokes a hidden button as you have now, you should be using a normal button to open the jQuery confirm dialog, not a command button sending an ajax request.
<h:button value="Delete" onclick="deletedialog('Do you want to delete the selected rows?'); return false;" />
Update: as to altering the button's value and disabling it, just pass the button itself into the JS function where you alter it the usual way:
<h:button value="Delete" onclick="deletedialog(this, 'Do you want to delete the selected rows?'); return false;" />
with
function deletedialog(button, message) {
button.value = "Processing...";
button.disabled = true;
// ...
}
Don't forget to put them back to normal values when enduser chooses Cancel in the confirm dialog.
Related
I am doing encryption for username and password in JavaScript using Jcryption algorithm. and decryption using Java . in that process before encryption process completion in JavaScript form is submitted .In Java I am not getting encrypted username and passwords. and I am getting normal values so I am prevented form submit and written code in the form submit after the encryption process completed I am calling submit event but form submitting multiple times.
give me suggestions is there any way to solve issues .or any alternate way to solve issues.
Thanks In Advance
My Html code
<form name="frm" method="post" action="/xsl-portal/xlogin" onSubmit="" target="_parent" autocomplete="off">
<input type="text" maxlength="45" name="eid1" id="eid1" />
<input type="hidden" maxlength="45" id="eid" name="eid" />
<input type="password" id="pw" name="pw" />
<input type="image" src="home-images/button-submit.png" id="submitButton" value="Submit" name="image" onclick="submitButtonClick();" />
<input type="hidden" value="" name="submit" id="submit"/>
</form>
Javascript code
var keys='';
function getKeys() {
$.jCryption.getKeys("/sakai-login-tool/EncryptionServlet?generateKeypair=true", function(
receivedKeys) {
keys = receivedKeys;
});
}
getKeys();
var encryptedUser='';
var encryptedPassword='';
/* form submit code*/
// $('#submitButton').on('click',function(){
function submitButtonClick(){
}
// });
$('form').submit(function(e) {
e.preventDefault();
var user=$('#eid1').val();
var password=$('#pw').val();
encryptionProcess(user,password).pipe(applyValues).pipe(function(){
console.log("eid"+$('#eid').val());
console.log("pw"+$('#pw').val());
$('form').submit();
});
})
;
function encryptionProcess(user,password){
var d= $.Deferred();
setTimeout(function() {
$.jCryption.encrypt(user, keys, function(encrypted) {
encryptedUser = encrypted;
console.log("printing user encryption:"+encryptedUser);
});
$.jCryption.encrypt(password, keys, function(encryptedPasswd) {
encryptedPassword = encryptedPasswd; /**
* As both userName and password are encrypted now Submit login
*/
console.log("printing password encryption:"+encryptedPassword);
});
d.resolve();
}, 10);
return d.promise();
}
function applyValues(){
var d1= $.Deferred();
setTimeout(function() {
$('#eid').val(encryptedUser);
$('#pw').val(encryptedPassword);
d1.resolve();
}, 10);
return d1.promise();
}
It is because of $('form').submit();. Since you are calling the jQuery submit() method, it will call the associated submit event handler causing a recursive cycle
Change it to use the dom element's submit() method, which will not result in the invocation of submit event handlers.
$('form')[0].submit();
//or e.target.submit();
Change your submit button to be a normal button. Listen for the click on this button and within that handler call $('form').submit();
The way you are doing at present will result in recursive submits.
I have an xhtml page for file Upload:
<p:fileUpload fileUploadListener="#{ContentRepositoryExplorerBean.upload}"
update="formId" dragDropSupport="true" multiple="true"/>
and i need to make confirmation dialog for user when for example he press "sign out"
What i do is:
<script>
var flag = false;
function setFlag(v) {
flag = v;
}
function getWarningMessage() {
if(flag == true) {
window.onbeforeunload = function() {
return 'Please do not leave this page until upload is done';
}
}
}
$('#logout').click(function() {
getWarningMessage();
});
</script>
and adding to fileUpload onstart and oncomplete
<p:fileUpload fileUploadListener="#{ContentRepositoryExplorerBean.upload}"
update="formId" dragDropSupport="true" multiple="true"
onstart="setFlag(true)" oncomplete="setFlag(false)"/>
but when i choose to stay on the page my upload is not showing in the list where it should be. Any ideas a appreciated
You can display dialog while upload is in process.
Create dialog (outside of your main form):
<p:dialog widgetVar="statusDialog" modal="true" draggable="false" header="Loading please wait.........."
closable="false" resizable="false" showHeader="false">
<p:outputLabel value="Uploading file..."></p:outputLabel>
</p:dialog>
change your p:fileUpload as
<p:fileUpload fileUploadListener="#{ContentRepositoryExplorerBean.upload}"
update="formId" dragDropSupport="true" multiple="true"
onstart="PF('statusDialog').show();"
oncomplete="PF('statusDialog').hide();"/>
Now if user does upload then it will show a popup with text message.
fixed this issue by change the script a bit:
<script type="text/javascript" >
var flag = false;
function setFlag(v) {
flag = v;
}
$(document).ready(function() {
var onclickFunc = new Function($('#logout').attr('onclick'));
$('#logout').on("click", function(event){
if(flag == true) {
event.stopImmediatePropagation();
alert("Please do not leave this page until upload is done");
}
}).click(onclickFunc).removeAttr('onclick');
})
</script>
I have a form which has 2 buttons: 'Submit' and 'Save'. Upon the submission of the form two kind of separate function run, depending on the button pressed. What I want to do is to call a function to check for empty fields when submit button is pressed.
Part of my code:
function valuecheck(){
var msg="";
if($F('entrepreneur_name')==""){
msg+="You need to fill the product name field!\n";
document.getElementById("entrepreneur_name").focus();
}
if($F('address')==""){
msg+="You need to fill in address!\n";
}
if (msg)
{alert(msg);
return false;
}
}
<?php
$chkbutton=$_POST['submit'];
switch ($chkbutton)
{
case "Submit":
// how to call the JavaScript function here..
...//rest of the code
?>
the form:
<input type="submit" style="width:10%" name="submit" value="Save" >
<input type="submit" style="width:10%" name="submit" value="Submit" >
how to call the javascript function inside the case "Submit":
Thanks in advance.
<input type="submit" style="width:10%" name="submit" value="Submit" onclick="Validate()" >
and
<script>
function Validate()
{
// your validation
}
</script>
You can do this on the form level prior submission:
<form name='myform' method='post' onSubmit="myFunction()">
And in your js function:
function myFunction()
{
if( !...)
return false; //don't submit the form
}
There are many ways to call JavaScript function from php function..
echo '<script type="text/javascript">'
, 'yourJSFunction();'
, '</script>';
Or you can do this way...
<?php
// some php stuff
?>
<script type="text/javascript">
yourJSFunction();
</script>
Hope it helps...
An alternative to sskoko's answer:
var submitButton = document.getElementById('submit-button');
submitButton.addEventListener('click', function(event) {
valuecheck();
}, false);
Though I have a sneaking suspicion that you will need to use event.preventDefault() to keep the form from submitting, when your values are invalid.
The method may have to be called either in the anonymous function passed to addEventListener(), or event may need to be passed into valuecheck() and then preventDefault() could be called down there. Play around with it and see.
I have a dataTable with a list of items and a checkbox for selecting an item to edit. Ticking an item and clicking the edit button pops up a component which has fields and update and cancel buttons. Here's what happens.
Dialog appears
I empty all fields and click UPDATE, required messages appear since all fields are empty, data is not saved
Click CANCEL, dialog disappears
Click and edit the same item again
Some fields are not showing. I checked the datatable and database, data for the item still exists. Just not showing on the edit dialog the 2nd time around.
I noticed that the fields not showing are only those that have NULL attributes. NOT NULL fields are fine. I wonder if this has something to do with sessions. (Using Primefaces for all components)
Code for the edit dialog
<p:dialog header="#{bundle.Edit}" modal="true" widgetVar="editDialog" resizable="false">
<h:form id="edit-form">
<p:messages id="edit-error" autoUpdate="true" closable="true"/>
<h:outputLabel value="#{bundle.Name}" for="name" /><span class="required">*</span>
<p:inputText id="name" value="#{controller.selected.name}" required="true" requiredMessage="#{bundle.Name} #{bundle.FieldIsRequired}" maxlength="45"/>
<h:outputLabel value="#{bundle.Input}" for="input" /><span class="required">*</span>
<h:selectOneRadio id="input" value="#{controller.selected.input}" required="true" requiredMessage="#{bundle.Input} #{bundle.FieldIsRequired}">
<f:selectItem itemLabel="◯ " itemValue="0" />
<f:selectItem itemLabel="☓ " itemValue="1" />
</h:selectOneRadio>
<h:outputLabel value="#{bundle.IsOption}" for="isOption" /><span class="required">*</span>
<h:selectOneRadio id="isOption" value="#{controller.selected.isOption}" required="true" requiredMessage="#{bundle.IsOption} #{bundle.FieldIsRequired}">
<f:selectItem itemLabel="◯ " itemValue="0" />
<f:selectItem itemLabel="☓ " itemValue="1" />
</h:selectOneRadio>
<h:outputLabel value="#{bundle.Remark}" for="remark" />
<p:inputTextarea id="remark" value="#{controller.selected.remark}"/>
<p:commandButton action="#{controller.update()}"
value="#{bundle.Save}"
actionListener="#{controller.prepareList()}"
oncomplete="handleEditDialog(xhr, status, args)"
update=":form:datatable :edit-form:edit-error"
/>
<p:commandButton value="#{bundle.Cancel}"
onclick="editDialog.hide(); reset();"
type="button"/>
</h:form>
</p:dialog>
Code for the update function
public String update() {
RequestContext context = RequestContext.getCurrentInstance();
try {
current.setUpdateDate(new Date());
Map<String, Object> param = JsfUtil.getExternal().getSessionMap();
int createUser = (Integer) param.get("LOGIN_ID");
Account account = accountFacade.find(createUser);
current.setUpdateUser(account);
getFacade().edit(current);
search();
prepareList();
JsfUtil.addSuccessMessage(ResourceBundle.getBundle(JsfUtil.getSessionBundle()).getString("Updated"));
updateOk = true;
current = null;
context.addCallbackParam("updated", true);
return "";
} catch (Exception e) {
if (e.getCause().getCause().getMessage().contains("uk_")) {
JsfUtil.addErrorMessage("edit-form:edit-error",JsfUtil.getResourceString("Duplicate"));
context.addCallbackParam("updated", false);
} else {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle(JsfUtil.getSessionBundle()).getString("PersistenceErrorOccured"));
context.addCallbackParam("updated", false);
}
return null;
}
}
Based on what you are describing I think the following scenario is happening. When you see the form and you delete all fields and you hit save, the components that have no validators are actually overwriting some of the previous property values of your bean. That's why when you reload it for a second edit, you'll notice that all the components that have a validator attached (e.g required = true) are appearing but those with no validators are blank. In reality, you are actually doing a partial update. What you actually need to do is mark all fields as required to avoid that problem.
My teammate just found out a fix for this one. There is a function on the controller generated by NetBeans called prepareList().
public String prepareList() {
recreateModel();
return "";
}
private void recreateModel() {
items = null;
}
Basically we added this on catch block of the update() function. It is called after every unsuccessful update and recreates the model. The bug existed because the field retained its state of not having a value after an unsuccessful update.
This is my login page
<h:outputText value="ENTER USERNAME" ></h:outputText>
<p:inputText value="#{treeBean.username}" id="user"></p:inputText>
<h:outputText value="ENTER PASSWORD" ></h:outputText>
<p:inputText value="#{treeBean.userpass}" id="pass"></p:inputText>
<p:commandButton value="GO" action="#{treeBean.checkuser}" onclick="redirect()"></p:commandButton>
<script type="text/javascript">
function redirect()
{
window.location="/arcpage/arc.jsf";
}
</script>
this is my treeBean.checkuser function
public void checkuser()
{
Connection con=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "root");
try
{
st.executeUpdate("USE ARCPAGE");
String update="SELECT * FROM USER WHERE USER_NAME=? AND USER_PASS=?";
PreparedStatement prest=con.prepareStatement(update);
prest.setString(1,username);
prest.setString(2,userpass);
ResultSet rs=prest.executeQuery();
if(rs.next()==false)
{
check="false";
}
else
{
check="true";
}
}}}
This is My main page:
<script type="text/javascript">
if(check!="true")
{
window.location="/arcpage/login.jsf";
}
</script>
<Main Page Content>
If I type the correct username-pass combination I am redirected to the login page instead of the main page. If I enter the correct combination again I am redirected to the main page. Even if I enter a wrong combination the second time I am redirected to the main page. I think the main page is being executed first and then the checkuser() is being executed so the value of check is not updated before the main page is displayed.
Why is this happening?
That's because you added some JavaScript function to the onclick which does the redirect. This is invoked when the user clicks the button. This in turn causes the JSF action being completely skipped. You also seem to be thinking that JSF and JavaScript runs in sync somehow. This is untrue. It are two completely distinct languages. JSF runs in webserver only, produces HTML/CSS/JS code and sends it to webbrowser. JS runs in webbrowser and intercepts on HTML DOM tree only.
To fix the problem, just remove the onclick and do the navigation in JSF action method. So:
<p:commandButton value="GO" action="#{treeBean.checkuser}" />
with
public String checkuser() {
User user = userService.find(username, password);
if (user == null) {
return "login";
} else {
return "arc";
}
}