javascript function call inside php function - java

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.

Related

AJAX with image button

I have tried different combinations of input type but how am I able to input a message without messing up the image? The purpose was to update the table without refreshing the page. To be more specific, when I clicked the image it should update the table on the side of the page. For many of the tutorial out there I saw people only use for onclick to call the ajax functions. Is there a good example for what I can do for the image button instead of the plain button?
For example:
<form name="bakery" action="TestMartController" method="post" >
<input type="hidden" name="action" value="dairy">
<input type="image" src="<%=request.getContextPath()%>/css/categories/dairy.jpg" onclick="loadXMLDoc">
The table I want to update is
<div id="refresh">
<table class="rightTable" border="1" width="70%">
<tr>
<th>Photo</th>
<th>Product and Description</th>
<th>Price</th>
<th>Orders</th>
<th>Quantity</th>
<th>Edit Quantity</th>
<th>Add Item </th>
</tr>
<c:forEach var="b" items="${bakery}">
...
</c:forEach>
</table>
</div>
Javascript file
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
document.getElementById("refresh").innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("POST", "bakery.jsp", true);
xmlhttp.send();
}
First of all you want a ajax call which makes post to a service and get datas and update your table.
I suggest to you learn how to use jquery and ajax call.
1- In your html define call method. Don't use form!
<img src="yourImage.jpg" onclick="getSomeData()">
2- Make post or get call to your service with jquery. And get Data.
function getSomeData(){
var url = "http://url";
$.post(url,{data:data})
.done(function(data){
//this data is your call result.
//do something
updateTable(data);
})
.fail(function(){
console.log('fail');
});
}
3- Create your gui function to change table.
function updateTable(){
//update your htmls
}

JQuery form on submit calling recursively

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.

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>

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();
}
});
});

Categories