I have a JSf form, I am tryin' to use jQuery Ui dialog plugin to submit the form.
here's the code snippet.
function confirmSubmit() {
$('#dialog').dialog('open');
return false;
}
$('#dialog').dialog({
autoOpen : false,
width : 400,
modal : true,
resizable : false,
buttons : {
"Submit Form" : function() {
document.myForm.submit();
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
<h:form id="myForm">
<h:commandLink action="#{Bean.search}" type="submit" onclick="return confirmSubmit()" id="search" styleClass="buttonSearch">
</h:commandLink>
The "document.myForm.submit();" part in the dialog box isn't working i.e., no calls goes to the server and in the server console I see the error:
11:45:32,738 SEVERE [lifecycle]
JSF1054: (Phase ID: RENDER_RESPONSE 6,
View ID: /PRT01/IMCM0101.jsp)
Exception thrown during phase
execution:
javax.faces.event.PhaseEvent[source=com.sun.faces.lifecycle.LifecycleImpl#ec333b]
The dialog box is appearing correctly but once i press the submit button "document.myForm.submit();" code is executed and the form is NOT submitted instead the above described error comes on the server console.
as you return false; it won't submit actually.
To make dialog working
$(document).ready(function() {
var $dialog = $('<div></div>')
.html('This dialog will show every time!')
.dialog({
autoOpen : false,
width : 400,
modal : true,
resizable : false,
buttons : {
"Submit Form" : function() {
document.myForm.submit();
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
});
and then just call
function confirmSubmit() {
$dialog.dialog('open');
return false;
}
It's done, some JSF parameters were missing. which jsf adds during form submissiom, I added them using jQuery:
$("a[id$='search']").click(function() {
var input = $("<input>").attr("type", "hidden").attr("name", "myForm:search").val("myForm:search");
$('#myForm').append($(input));
$("p#dialog-email").html(titleVar);
$('#dialog').dialog('open');
});
Related
Good day,
The following is my jsp code:
<s:form beanclass="c.c.i.c.app.profile.ui.ChangePasswordAction" method="post" name="form1">
<!-- some others code here -->
<sx:row cssClass="button_row">
<sx:input name="updatePassword" image="submit"/>
</sx:row>
</s:form>
And this is my jquery:
<script type="text/javascript">
$(':input[name=updatePassword]').click(function() {
var answerProceed = confirm("Do you wish to proceed with the changes?");
if( answerProceed ){
var form = $("form[name=form1]");
form.attr("action", '<s:url beanclass="c.c.i.c.app.profile.ui.ChangePasswordAction" event="update"/>');
form.submit();
} else {
return false;}
});
</script>
We can see that, in the jQuery, it will trigger a update event to ChangePasswordAction.
However, currently I have a issue, which is sometimes it will trigger 2 times, its not always happen, but the happen rate is about 50%.
The following is the trigger log I get from my application log:
2019-06-26 18:19:13.658 [WebContainer : 31] TRACE o.s.w.c.s.XmlWebApplicationContext - [bmaker] - Publishing event in Root WebApplicationContext: org.springframework.security.event.authorization.AuthorizedEvent[source=FilterInvocation: URL: /common/change_password.html?update=&__stoken=1a47d3a9-29e8-4904-b204-3cb9fc0129f0]
2019-06-26 18:19:13.660 [WebContainer : 26] TRACE o.s.w.c.s.XmlWebApplicationContext - [bmaker] - Publishing event in Root WebApplicationContext: org.springframework.security.event.authorization.AuthorizedEvent[source=FilterInvocation: URL: /common/change_password.html?update=&__stoken=1a47d3a9-29e8-4904-b204-3cb9fc0129f0]
Anyone know what wrong with the code?
If an <input/> is of type="submit" in a form you have to use preventDefault() if you want to check for confirmation before you submit the form.
You can pass e as parameter in your listener as an Event implementation parameter like MouseEvent (because of the click event) in this case.
For example :
$(':input[name=updatePassword]').click(function(e) { // <-- e implements Event
e.preventDefault(); // <-- prevent the submit of the form
var answerProceed = confirm("Do you wish to proceed with the changes?");
if (answerProceed) {
var form = $("form[name=form1]");
// var form = e.currentTarget.form; you can do this
// var form = this.form; or you can do this, "this" is implicit clicked element
form.attr("action", '<s:url beanclass="c.c.i.c.app.profile.ui.ChangePasswordAction" event="update"/>');
form.submit();
}
else {
return false;
}
});
You can access the form of an element by doing .form on an element, see
HTMLSelectElement.form
See
Event.preventDefault()
Event
MouseEvent
I have the form
<aui:form action="<%= editURL %>" method="POST" name="fm">
<aui:fieldset>
<aui:input name="name" />
<aui:input name="url" />
<aui:input name="address" />
</aui:fieldset>
<aui:button-row>
<aui:button type="submit" />
<aui:button name="cancel" value="Cancel"/>
</aui:button-row>
</aui:form>
and this piece of javascript code which is inserting into database twice I don't know why.
<aui:script use="aui-base,aui-form-validator,aui-io-request">
AUI().use('aui-base','aui-form-validator',function(A){
var rules = {
<portlet:namespace/>name: {
required: true
},
<portlet:namespace/>url: {
url: true
},
<portlet:namespace/>address: {
required: true
},
};
var fieldStrings = {
<portlet:namespace/>name: {
required: 'The Name field is required.'
},
<portlet:namespace/>address: {
required: 'The Address field is required.'
},
};
alert("validator");
new A.FormValidator({
boundingBox: '#<portlet:namespace/>fm',
fieldStrings: fieldStrings,
rules: rules,
showAllMessages:true,
on: {
validateField: function(event) {
},
validField: function(event) {
},
errorField: function(event) {
},
submitError: function(event) {
alert("submitError");
event.preventDefault(); //prevent form submit
},
submit: function(event) {
alert("Submit");
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
alert("inside success");// not getting this alert.
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
}
}
});
});
</aui:script>
However if I add the following piece of code, which is redundant because it is already present inside the submit block of above code and is not triggered any way because I do not have any save button in the form, then the value is inserted only once.
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
This code generates Uncaught TypeError: Cannot read property 'on' of null which I think is because there is no save button in the form. But adding this code, the value is inserted into database just once which is what I want but the logic is flawed. How can I get the results I want by just by using the first piece of code?
The insertion was happening twice. Once from the default form submit and other from the A.io.request. Adding this piece of code
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
resulted in the insertion only once. This code has obviously no relevance because there is no save button in the form. Hence there was Uncaught TypeError: Cannot read property 'on' of null which masked the flaw and prevented the form from being submitted twice.
Removing the above piece of code and preventing the default submit (by adding onSubmit="event.preventDefault(); in the form tag) resolves the issue.
For couple of days, I am trying to see as why my action is not getting invoked in this particular form.
My Form is something like below and I have struts URL tags which I am using along with Bootstrap framework:
<s:form action="RegisterUser" cssClass="form-horizontal" id="id-register-form" method="post">
Couple of Struts 2 UI tags
</s:form>
My Register user action is very simple with just an execute method in it which returns string "success":
public class RegisterUser extends ActionSupport {
public RegisterUser() {
}
#Override
public String execute() throws Exception {
System.out.println("Inside execute method test 1!");
return "success";
}
}
My struts.xml for the above looks something like below:
<action name="RegisterUser" class="Mypackage.RegisterUser" method="execute">
<result name="success">/WEB-INF/views/usermanagement/register-success.jsp</result>
<result name="error">/WEB-INF/views/usermanagement/register-error.jsp</result>
</action>
But whenever I click the submit button of the form,form submission is never triggered. I have client side validation with jquery with jquery validate library and then doing server side with struts validation framework,but I believe issue is not related to validation but more on action mapping side or something related to submit button.Below is my submit button,
<s:submit type="button" cssClass="btn btn-primary" value="Create Account" cssStyle="float:left;">Create Account</s:submit>
Appreciate if someone can take a look and give me some insights. I am on Glassfish v4 and using Netbeans IDE and my Struts 2 is 2.3.15.3 on win 8.1
Here is my JS code for client side validation with jQuery:
$(document).ready(function() {
// validate the comment form when it is submitted
$("#id-register-form").validate({
errorPlacement: function(error, element) {
if (element.attr("name") == "Email") {
error.appendTo('#error-Email');
}
else if (element.attr("name") == "Password") {
error.appendTo('#error-Password');
}
else if (element.attr("name") == "ConfirmPassword") {
error.appendTo('#error-ConfirmPassword');
}
else if (element.attr("name") == "AgreetoPolicy") {
error.appendTo('#error-Agree');
}
},
rules: {
Email: {
required: true,
email: true
},
Password: {
required: true,
minlength: 5
},
ConfirmPassword: {
required: true,
minlength: 8,
equalTo: "#Password"
},
AgreetoPolicy: "required"
},
messages: {
Email: "<small>Please enter a valid email address</small>",
Password: {
required: "<small>Please provide a password</small>",
minlength: "<small>Your password must be at least 8 characters long</small>"
},
ConfirmPassword: {
required: "<small>Please provide a password</small>",
minlength: "<small>Your password must be at least 5 characters long</small>",
equalTo: "<small>Please enter the same password as above</small>"
},
AgreetoPolicy: "<strong><small>Please accept our policy</small></strong>"
}
});
});
Try to change this code where messages
Email: {
required: "<small>Please enter a valid email address</small>",
email: "Email addresses are of the form user#host."
}
Yup issue is resolved now.It was my broken Jquery validation code that was responsible for not submitting the form...Thanks Roman and Andrea for your help and assistance.Appreciate it.
I have a slight problem with my jQuery and I can't quite figure out where my problems lies, so if anyone could give me a hand with it is greatly appreciated.
I am using a jQuery function that when my #add div gets clicked, a JavaBean is called which adds the current page to the session user and when the #remove div gets clicked, a similar process is carried out that removes the current page from the user.
My problems starts when I try to check with the collection whether the current page is already associated with the user and if so display the #remove div and otherwise display the #add div.
Below is my script:
<script>
$(document).ready(function() {
$("#viewshow-text").load(function(){
if(${userShowDetails}) { <%-- this var can either be true or false depending on whether the page is associated with the user or not --%>
$('#removeshow').show(),
$('#addshow').hide();
} else {
$('#addshow').show(),
$('#removeshow').hide();
}
});
$("#add").click(function() {
$.post("addshow", {
item : "${param.show}"
}, function(data, status) {
}, function() {
<%-- hide a div and display the other --%>
$this.find('#addshow').hide(),
$this.find('#removeshow').show();
});
});
$("#remove").click(function() {
$.post("removeshow", {
item : "${param.show}"
}, function(data, status) {
}, function() {
$this.find('#removeshow').hide(),
$this.find('#addshow').show();
});
});
});
</script>
My div elements in question are as follows:
<div class="viewshow-text">
<c:if test="${!empty USER}"> <%-- only display if a user is logged in --%>
<div id="addshow" class="viewshow-button viewshowAdd-button">
<a id="add" href="#">Add to calendar</a>
</div>
<div id="removeshow" class="viewshow-button viewshowRemove-button">
<a id="remove" href="#">Remove from calendar</a>
</div>
</c:if>
</div>
I have no issues with my JavaBean properties as I double checked and they are displaying the contents expected:
$(document).ready(function() {
$(if(false) {
$('#removeshow').show(),
$('#addshow').hide();
} else {
$('#addshow').show(),
$('#removeshow').hide();
});
When the page is not in the user list.
Here try this,
<script>
$(document).ready(function() {
if(${userShowDetails}) {
$('#removeshow').show(),
$('#addshow').hide();
} else {
$('#addshow').show(),
$('#removeshow').hide();
};
$("#add").click(function() {
$.post("addshow", {
item : "${param.show}"
}).done(function(data) {
$('#addshow').hide(),
$('#removeshow').show();
});
});
$("#remove").click(function() {
$.post("removeshow", {
item : "${param.show}"
}).done(function(data) {
$('#removeshow').hide(),
$('#addshow').show();
});
});
});
</script>
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.