JQuery form on submit calling recursively - java

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.

Related

message after form validation

I have a JSP page which has several input fields and a servlet validates the fields when I click on the submit button and redirects to another page.
I would like to add a popup window: "all the fields are ok" after a correct server-side validation.
So I started with:
<form ="alert('success');">
<input type="submit" value="submit">
</form>
The problem is that "success" is printed even if the fields are incorrect.
I thought about setting a parameter in the
protected void doPost(HttpServletRequest request,HttpServletResponse response, which calls an execute() function to say if things are OK or not but I do not know how to get this parameter just after the submit so I could make a conditional:
if (checkSubmitParameter == OK )
callsPopup()
Try something like this (see jsfiddle):
<script>
function checkit(){
var val = document.getElementById('txt').value;
if(val == "good"){
alert("success");
}else{
alert("failure!");
}
}
</script>
<form onsubmit='checkit()'>
<input type='text' id="txt" />
<input type='submit' value='Submit' />
</form>

javascript function call inside php function

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.

Apache Wicket : Onclick of a form button, I need to call a small javascript function

Onclick of a form button, I need to call a small javascript function. This javascript function should validate some fields in the same form and then call the onSubmit() of the form which is in java.
Main Idea is that let validate happen in client side and not in java.
Complete idea :
I have help.html file as shown below :
<form wicket:id="form">
<input type="text" wicket:id="one"/>
<input type="text" wicket:id="two"/>
<input type="submit" wicket:id="save"/>
</form>
In help.java, I created a WebMarkupContainer and added this form with this submit button :
container.add(new Button("save") {
#Override
public void onSubmit() {
//saved
}
});
On click of the button in html, it calls onSubmit() and here we can do a validation on the text box values.
But I need to do all the validations in the HTML page itself.
OnClick of the Button Save, it should call a javascript funciton as shown below :
<form wicket:id="form">
<input type="text" wicket:id="one"/>
<input type="text" wicket:id="two"/>
<input type="submit" wicket:id="save" onclick="validateRange()"/>
</form>
JavaScript :
function validateRange(){
//logic
//Submit the form
}
Can this be done?
You need an AjaxSubmitLink or something like this. The you need to create a new IAjaxCallListener
public class MyAjaxCallListener implements IAjaxCallListener{
#Override
public CharSequence getBeforeHandler(Component component) {
return YOUR_JAVA_SCRIPT;
}
#Override
public CharSequence getBeforeSendHandler(Component component) {
return YOUR_JAVA_SCRIPT;
}
// ... not needed overrides can return null
}
Then in your AjaxSubmitLink you can add this AjaxCallListener
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getAjaxCallListeners().add(new MyAjaxCallListener());
}
Here you have an example Try if yourself
HTML:
<form id="form" action="#">
<input id="text" type="text"/>
<input type="button" onclick="validate()" value="TEST"/>
</form>
JS:
function validate() {
var value = document.getElementById("text").value;
if (value == "") {
alert("you have to write something");
return false;
}
else
document.getElementById("form").submit();
}

How to change a form value dynamically and submit during onclick

I am using onclick event in anchor tag. when i clcik the anchor, I am invoking a java script function where I change the value of one input element and submit the form. The value is changed but the form does not submit the value. Please help me on this. FYI that if i create an element and add in the form before submission, it works. Why is not working in the first scenario.
<form name="form" >
<input type="hidden" name="input" value="test"/>
<a onclick='testMethod("test")'>click </a>
</form>
script used is
function testMethod(value)
{
if(serviceName != null && jQuery('#form') != null)
{
document.forms['form'].getElementById('input').value = value;
document.forms['form'].action = jQuery('#newAction').val();
document.forms['form'].submit();
}
}
The main problem here is you're trying to access the input by id when it doesn't have one set:
(Added id to form and id to input so we can select them easily):
<form name="form" id="form">
<input type="hidden" name="input" id="input" value="test" />
<a onclick='testMethod("test")' >click</a>
</form>
And the javascript to match (updating to use jQuery's selectors since you indicated you have jQuery support available):
function testMethod(value)
{
var form = $('#form');
if(serviceName != null && form.length)
{
$('#input').val(value);
form.attr('action', $('#newAction').val());
form.submit();
}
}
You can also update your code such that you aren't including the binding to the onclick method in the DOM, but attaching to it directly in javascript:
Changing the a element to have an ID:
<form name="form" id="form">
<input type="hidden" name="input" id="input" value="test" />
<a id="submitLink">click</a>
</form>
The javascript could now look like this:
$(document).ready(function() {
$('#submitLink').on('click', function(event) {
event.preventDefault();
var form = $('#form');
if(serviceName != null && form.length)
{
$('#input').val(value);
form.attr('action', $('#newAction').val());
form.submit();
}
});
});

Enable/Disable checkbox based on Jquery Ajax Call to Server side method upon dropdown change

Looking for a way to call Server side method (Java) upon dropdown selection-change and based on the server output (TRUE OR FALSE), enable or disable few checkboxes. Would highly appreciate if anyone can provide recommendations around the same.
I've coded a quick example to show you how this would be done. First you will need to set up your java app to allow ajax calls. The java app will need to take in as input a single post variable name selected which is the value of the selected option in the dropdown menu. The java app will then need to return a json string formatted similar too:
{
"disabled":[
"1",
"3",
"5"
]
}
The 1, 3, and 5 represent the ids of the checkboxes you would like to be disabled. These can be any ids of any of the checkboxes. If it isn't in this array, it will be set to enabled by default.
HTML:
<select id="choiceSelector">
<option value="1">Something 1</option>
<option value="2">Something 2</option>
</select>
<br/><br/>
<div id="changingCheckboxes">
<input type="checkbox" name="" id="1"><br/>
<input type="checkbox" name="" id="2"><br/>
<input type="checkbox" name="" id="3"><br/>
<input type="checkbox" name="" id="4"><br/>
<input type="checkbox" name="" id="5"><br/>
<input type="checkbox" name="" id="6">
</div>​
Javascript/jquery
function UpdateCheckBoxStatus ()
{
var CurrentChoice = $('#choiceSelector').val();
$.ajax({
url: "####YOUR JAVA APP URL####",
data: { "selected": CurrentChoice },
type: "post",
dataType: "json",
success: function (data)
{
SetCheckbox($('#changingCheckboxes').children("input:[type='checkbox']"), true);
$.each(data.disabled, function ()
{
SetCheckbox($('#changingCheckboxes #' + this), false);
});
}
});
}
/// Sets the checkbox to enabled or disabled
/// #param th Jquery reference of one or more checkboxes
/// #param usable True/False if the checkbox is enabled/disabled
function SetCheckbox (th, usable)
{
if (usable)
th.removeAttr("disabled");
else if (!usable)
th.attr("disabled", true);
}
$(function ()
{
$('#choiceSelector').change(UpdateCheckBoxStatus);
UpdateCheckBoxStatus(); //run for page load
});
Also, here is the jsfiddle of it: http://jsfiddle.net/bpstw/1/
Hope that helps.
Sure. Add a .change() handler to the drop-down element, within the handler make a $.ajax() request passing the selected value to your Java (possibly jQuery's shortcut ajax methods $.get() or $.post() would be easier than $.ajax()), and within the Ajax success callback check the server's response and enable or disable the relevant checkboxes.
Another similar solution for Radio button including Server side code in Java.
Jquery/HTML
Value1
Value2
Value3
<span id="changingCheckboxes">
<label for="group1">One</label>
<input type="radio" name="group1" id="1" value="option1"/>
<label for="group1">Two</label>
<input type="radio" name="group1" id="2" value="option2"/>
<label for="group1">Three</label>
<input type="radio" name="group1" id="3" value="option3"/>
<label for="group1">Four</label>
<input type="radio" name="group1" id="4" value="option4"/>
</span>
Jquery
function UpdateCheckBoxStatus () {
var CurrentChoice = $("#dropDownId").val();
$.ajax({
url: "/serverSideUrl",
data: { "selectedDropDownId": CurrentChoice },
type: "post",
dataType: "json",
success: function (data) {
SetCheckbox($("#changingCheckboxes").children("input:[type='radio']"), true);
$.each(data.disabled, function () {
SetCheckbox($("#changingCheckboxes #" + this), false); });
}
});
}
function SetCheckbox (th, state) {
if (state) th.removeAttr("disabled");
else if (!state) th.attr("disabled", true);
}
$('#dropDownId').change(UpdateCheckBoxStatus);
Java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String selectedValue = request.getParameter("dropDownId");
YourDao yourDao = new YourDao();
Map<String, List<String>> disabledOptions = cycleDao.determineStateDropDown(selectedTool);
String json = new Gson().toJson(disabledOptions);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}

Categories