I am having two buttons in a form ques and ans. When i click the ques button the same form with some text-fields will get open and in the form I've two buttons add and clear. By clicking add the entered field will be entered to the database. Like wise the same thing for clicking the answer button. I'm having one onsubmit=return valid() for both the buttons. I've to write separate script for both buttons, checking the conditions. But I'd written for only answer button. I dont know how to write for both buttons in one function valid(). Please tell me how to write for both buttons inside a function.
function valid()
{
var quest=document.getElementById('ques1').value;
var cno=document.getElementById('cno').value;
var pno=document.getElementById('pno').value;
quest1=trim(quest1);
pno=trim(pno);
cno=trim(cno);
if(quest=="")
{
alert("Please enter Question");
document.getElementById('ques1').focus();
return false;
}
else if( pno=="")
{
alert("Please enter valid Page No");
document.getElementById('pno').focus();
return false;
}
else if (cno=="")
{
alert("Please Select Chapter No");
document.getElementById('cno').focus();
return false;
}
}
You can do something like this
function validate(button_value) {
if(button_value=='test1') {
if(document.getElementById('rest1').value=="") {
alert('Blank for input 2');
return false;
}
} else if(button_value=='test') {
if(document.getElementById('rest').value=="") {
alert("Blank for input 1");
return false;
}
}
}
The HMTL I tested in:
<form method="POST" action="" onsubmit="return validate(this.submited);">
<input type="text" name="rest" id="rest" value=""/>
<input type="text" name="rest1" id="rest1" value=""/>
<input onclick="this.form.submited=this.value;" type="submit" id="test" value="test"/>
<input onclick="this.form.submited=this.value;" type="submit" id="test1" value="test1"/>
</form>
Hope this helps
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validate(this.submited);">
Question : <input type="text" name="ques">
Answer : <input type="text" name="ans">
<input type="submit" name="subques" value="Ask Question"/> <input type="submit" name="subans" value="Reply Answer"/>
</form>
<hr>
<?php
if(isset($_POST['subques']))
{
if(isset($_POST['ques']))
{
if($_POST['ques'] != '' && $_POST['ques'] != NULL)
{
echo "Your question is: " . $_POST['ques'];
}
}
}
if(isset($_POST['subans']))
{
if(isset($_POST['ans']))
{
if($_POST['ans'] != '' && $_POST['ans'] != NULL)
{
echo "Your answer is: " . $_POST['ans'];
}
}
}
?>
Related
Im trying to validate a single textbox on the same page using PHP but am unable to get the errors to show. When i click submit and there is nothing in the textbox it works by not letting it go to the next page but it does not show the errors. Here is my code.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['IGN'] == ""){
$errors="Please enter a IGN";
}
if (isset($errors)){
echo $errors;
}
}
?>
<form method="post" action="Queston1.php">
<label for="IGN" class="questionText">IGN (In Game Name)</label><br />
<input type="text" name="IGN" /><br />
<input type="submit" name="start" value="start" />
</form>
I have tried it with and without the if (isset($errors)) to see if that was the problem but both times i get the same result.
Can anyone see or know how to fix this?
You should use jQuery or Javascript to validate before submitting the form.
But instead of
if($_SERVER['REQUEST_METHOD'] == 'POST'){
Try
$errors = '';
if(isset($_POST['IGN'])){
if($_POST['IGN'] == ''){
$errors .= 'Please Enter a IGN';
}
}
if($errors!=''){
echo $errors;
}
Try something like this:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['IGN'] == ""){
echo "Please enter a IGN";
}
else {
header('Location: question.php');
}
}
?>
<form method="post" action="">
<label for="IGN" class="questionText">IGN (In Game Name)</label><br />
<input type="text" name="IGN" /><br />
<input type="submit" name="start" value="start" />
</form>
hi guys i am kinda new to php and i am trying to add validation on to the form. i want it so the form will not submit if it is empty.
<form id="form1" name="form1" method="post" action="category_created.php">
Enter a New Category Name :
<label for="cat"></label>
<input type="text" name="cat" id="cat" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
and the form is being submitted to the file where the contents is being submitted to the database:
<?php
//category name received from 'new_category.php' is stored in cariable $cat
$cat=$_POST['cat'];
$qry=mysql_query("INSERT INTO category(category)VALUES('$cat')", $con);
if(!$qry)
{
die("There Was An Error!". mysql_error());
}
else
{
echo "<br/>";
echo "Topic ".$cat." Added Successfully";
echo "<br/>";
}
?>
any help will be appreciated
thanks
use onsubmit and validate like below
<form onsubmit="return validate()" id="form1" name="form1" method="post" action="category_created.php" >
.....
</form>
and in javasctipt
<script>
function validate(){
if(document.getElementById('cat').value.length<1)
{
alert('Please enter the Category Name');
return false;
}
else
{
return true;
}
}
</script>
or you could submit the form via ajax, in the db-file you check whether the fields are empty, ifso echo an error message and print it via javascript. By doing this you can style everything the way you want to :)
I am having trouble with a same page AJAX/JavaScript/PHP Captcha validation code. The original code is from http://www.phpcaptcha.org. We are using a third party site to store all of our form data into a database that is edited by multiple people. Lately we've been receiving a ton of spam so we're trying to implement this Captcha.
I'll cut to the chase here. The code is set to 'return false' every time. I need it to 'return true' if certain conditions are met. The code is as follows:
<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!
$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
// EMAIL is edited out for school use
if( isset($_POST['captcha_code']))
{
$a = array("error"=>0);
print json_encode($a);
}
// Process the form, if it was submitted (Original Code called process_si_contact_form())
process_si_zoho1();
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="text/javascript">
//variables not part of original code
function reloadCaptcha()
{
//original code ElementId labled 'captcha_code'
document.getElementById('captcha').src ='securimage_show.php?sid=' + Math.random();
}
var r, Submit;
function processForm()
{
new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
method: 'post',
//Original code did not state 'zoho1'
parameters: $('zoho1').serialize(),
onSuccess: function(transport) {
//Re-edited for school use. Not original code
try {
r = transport.responseText.evalJSON();
Submit = r.submit
if (r.error == 0) {
alert('Congrats!');
reloadCaptcha();
} else {
alert("There was an error with your submission.\n\n" + r.message);
}
} catch(ex) {
alert("There was an error parsing the json");
}
},
onFailure: function(err) {
alert("Ajax request failed");
}
});
return Submit;
}
}
</script>
The process_si-zoho1() is as follows:
<?php
//Original code process called 'process_si_contact_form())
function process_si_zoho1()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && #$_POST['do'] == 'contact') {
// if the form has been submitted
foreach($_POST as $key => $value) {
if (!is_array($key)) {
// sanitize the input data
if ($key != '-------') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$captcha = $_POST['captcha_code']; // the user's entry for the captcha code
$errors = array(); // initialize empty error array
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered';
}
}
if (sizeof($errors) == 0) {
// no errors, send the form
//Edited out mail function from original code
//Changed JSON return array on successful validation to send new variable '$Submit' via serialized $entry
$Submit = true;
$entry = array('error' => 0, 'submit' => $Submit);
die(json_encode($entry));
} else {
$errmsg = $captcha_error;
foreach($errors as $key => $error) {
// set up error messages to display with each field
$errmsg .= " - {$error}\n";
$Submit = false;
}
//Added $Submit to the return array
$return = array('error' => 1, 'message' => $errmsg, 'submit' => $Submit);
die(json_encode($return));
}
} // POST
} // function process_si_zoho1()
?>
The 'processForm()' runs when the submit button is clicked. I'm sure i'm missing something really simple here, I'm just too involved in it. I really appreciate your help
I know that the value of 'Submit' is not defined until the PHP in the AJAX.Request() runs but I can't figure out how to define the variable from the start. FYI, the variables 'r' and 'Submit' are all declared outside the function itself so are global variables. If I try to insert a return into the try/catch it will always give me the error in the catch "There was an error parsing the json." Also, with the code as it is now, it will always give me the same error and submit the form anyways, as the value of Submit is blank. Even if I define the Global variable "Submit" as "false" it still returns as though it is blank.
If anything other than 'return false' is declared at the bottom of the function, it will submit the form without validating the Captcha. I'm very new to all this, but I've been researching for almost 2 weeks now for 4-8 hours a day and have yet to find a working code. Is it even possible? I mean, other websites use same page validation and submit to third party databases right?
I can provide more code if needed, but the problem seems to be here. If I don't try to change the return, the Captcha validates fine and the 'if (r.error == 0)' code executes fine. I have even added an alert to show the value of 'Submit' just to verify the data is transferring between the functions.
I'm at my wit's end here. I would appreciate any help.
Thanks,
Matt
The complete code (minus details) is as follows:
<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!
$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
// EMAIL is edited out for school use
// Process the form, if it was submitted (Original Code called process_si_contact_form())
process_si_zoho1();
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="text/javascript">
//variables not part of original code
function reloadCaptcha()
{
//original code ElementId labled 'captcha_code'
document.getElementById('captcha').src = '/securimage_show.php?sid=' + Math.random();
}
var r, Submit;
function processForm()
{
new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
method: 'post',
//Original code did not state 'zoho1'
parameters: $('zoho1').serialize(),
onSuccess: function(transport) {
//Re-edited for school use. Not original code
try {
r = transport.responseText.evalJSON();
Submit = r.submit;
if (r.error == 0) {
alert('Congrats!');
reloadCaptcha();
} else {
alert("There was an error with your submission.\n\n" + r.message);
}
} catch(ex) {
alert("There was an error parsing the json");
}
},
onFailure: function(err) {
alert("Ajax request failed");
}
});
return false;
}
}
</script>
</head>
<body>
<form action="----------" id="zoho1" method="POST" name="leadForm" onsubmit="return processForm()">
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input type="hidden" name="do" value="contact" /><br />
<p>
<label for="First Name">First Name</label><br />
<input class="required" maxlength="40" name="First Name" type="text" /></p>
<p>
<label for="Last Name">Last Name</label><br />
<input class="required" maxlength="80" name="Last Name" type="text" /></p>
<p>
<label email="" for="">Email</label><br />
<input class="required validate-email" maxlength="100" name="Email" type="text" /></p>
<p>
<label for="Phone">Main Phone</label><br />
<input class="required" maxlength="30" name="Phone" type="text" /></p>
<p>
<label for="Mobile">Mobile Phone</label><br />
<input maxlength="30" name="Mobile" type="text" /></p>
<p>
<label for="State">State</label><br />
<select class="required validate-selection" name="State"><option selected="selected" value="-None-">-None-</option><option value="AL">AL</option><option value="AK">AK</option><option value="AZ">AZ</option><option value="AR">AR</option><option value="CA">CA</option><option value="CO">CO</option><option value="CT">CT</option><option value="DE">DE</option><option value="DC">DC</option><option value="FL">FL</option><option value="HI">HI</option><option value="ID">ID</option><option value="IL">IL</option><option value="IN">IN</option><option value="IA">IA</option><option value="KS">KS</option><option value="KY">KY</option><option value="LA">LA</option><option value="ME">ME</option><option value="MD">MD</option><option value="MA">MA</option><option value="MI">MI</option><option value="MN">MN</option><option value="MS">MS</option><option value="MO">MO</option><option value="MT">MT</option><option value="NE">NE</option><option value="NV">NV</option><option value="NH">NH</option><option value="NJ">NJ</option><option value="NM">NM</option><option value="NY">NY</option><option value="NC">NC</option><option value="ND">ND</option><option value="OH">OH</option><option value="OK">OK</option><option value="OR">OR</option><option value="PA">PA</option><option value="RI">RI</option><option value="SC">SC</option><option value="SD">SD</option><option value="TN">TN</option><option value="TX">TX</option><option value="UT">UT</option><option value="VT">VT</option><option value="VA">VA</option><option value="WA">WA</option><option value="WV">WV</option><option value="WI">WI</option><option value="WY">WY</option><option value="GA">GA</option></select></p>
<!--<div><label for="Mailing Zip">Mailing Zip</label><br /><input type="text" maxlength="30" name="Mailing Zip" /></div>--><!--<div><label for="Mailing Country">Mailing Country</label><br /><input type="text" maxlength="30" name="Mailing Country" /></div>-->
<p>
<label for="----------">----------</label><br />
<select class="required validate-selection" name="----------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option></select></p>
<p>
<label for="-------">----------</label><br />
<select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option></select></p>
<p>
<label for="-------">------------</label><br />
<select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="---------">-----------</option></select></p>
<p>
<label for="-------">Intended Degree</label><br />
<select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="--------------">-------------</option><option value="-------------">-------------</option><option value="-------------">--------------</option></select></p>
<p>
<label for="-------">How did you hear about TTU?</label><br />
<textarea class="required" height="250" maxlength="1000" name="-------" width="250"></textarea></p>
<p>
<label for="Description">Comments</label><br />
<textarea height="250" maxlength="1000" name="Description" width="250"></textarea></p>
<img id="captcha" src="/securimage_show.php" alt="CAPTCHA IMAGE" />
<input type="text" id="enterVerify" name="captcha_code" size="10" maxlength="6" />
<input type="button" id="reload" name="Reload" value="Reload" onClick="reloadCaptcha()">
<input class="form-button" name="save" type="submit" value="Submit" />
</form>
</body>
</html>
<?php
//Original code process called 'process_si_contact_form())
function process_si_zoho1()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && #$_POST['do'] == 'contact') {
// if the form has been submitted
foreach($_POST as $key => $value) {
if (!is_array($key)) {
// sanitize the input data
if ($key != '-------') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$captcha = $_POST['captcha_code']; // the user's entry for the captcha code
$errors = array(); // initialize empty error array
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered';
}
}
if (sizeof($errors) == 0) {
// no errors, send the form
//Edited out mail function from original code
//Changed JSON return array on successful validation to send new variable '$Submit' via serialized $entry
$Submit = true;
$entry = array('error' => 0, 'submit' => $Submit);
die(json_encode($entry));
} else {
$errmsg = $captcha_error;
foreach($errors as $key => $error) {
// set up error messages to display with each field
$errmsg .= " - {$error}\n";
$Submit = false;
}
//Added $Submit to the return array
$return = array('error' => 1, 'message' => $errmsg, 'submit' => $Submit);
die(json_encode($return));
}
} // POST
} // function process_si_zoho1()
?>
<?php
if( isset( $_POST['captcha'] ))
{
$a = array("error"=>0);
print json_encode( $a );
exit();
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js" ></script>
</head>
<body onload="processForm()">
<form id="formtest" action="" method="POST">
<input type="text" name="captcha" value="1vfvrfr">
</form>
<script>
var r, Submit;
function reloadCaptcha(){}
function processForm()
{
new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
method: 'post',
//Original code did not state 'zoho1'
parameters: $('formtest').serialize(),
onSuccess: function(transport) {
//Re-edited for school use. Not original code
try {
r = transport.responseText.evalJSON();
Submit = r.submit
if (r.error == 0) {
alert('Congrats!');
reloadCaptcha();
} else {
alert("There was an error with your submission.\n\n" + r.message);
}
} catch(ex) {
alert("There was an error parsing the json");
}
},
onFailure: function(err) {
alert("Ajax request failed");
}
});
return Submit;
}
</script>
</body>
</html>
Thanks for all the help. I did some more research, the problem was in the JavaScript (my least experienced portion of code). I simply added to the:
if (r.error == 0)
document.forms['formname'].submit();
Thanks for the help guys! I'll definitely be using this forum again!
i am new to web development.
I have a question about validating user input data in a single php page:
this is my code
<html>
<head>
<script lanauge="JavaScript" type="text/javascript">
function validate_skill_name()
{
if (document.worker.skill_name == null
|| document.worker.skill_name == "") {
alert("skill name field is incorrect");
document.worker.skill_name.focus();
return false;
}
return true;
}
function validate_skill_id()
{
if (document.worker.worker_id1 == null
|| isNaN(document.worker.worker_id1)) {
alert("skill: worker id 1 field is incorrect");
document.worker.worker_id1.focus();
return false;
}
return true;
}
function validate_time_id()
{
if (document.worker.worker_id2 == null
|| isNaN(document.worker.worker_id2)) {
alert("time: worker id 2 field is incorrect");
document.worker.worker_id2.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<h1> Select Workers </h1>
<form name="worker" action="" method="post" onsubmit="return(validate_skill_name());">
Skill Name: <input type="text" name="skill_name"/><br />
<input type="submit" value="submit me!"/>
</form>
<h1> Get Worker Skill </h1>
<form name="worker" action="" method="post" onsubmit="return(validate_skill_id());">
ID: <input type="text" name="worker_id1"/> <br />
<input type="submit" value="submit me!"/>
</form>
<h1> Get Worker Available Time </h1>
<form name="worker" action="" method="post" onsubmit="return(validate_time_id());">
ID: <input type="text" name="worker_id2"/> <br />
<input type="submit" value="submit me!"/>
</form>
<?php
require_once "../logic.php";
if ($_POST) {
$result = NULL;
if (array_key_exists('worker_id2', $_POST)) {
$result = logic_get_worker_available_time($_POST['worker_id2']);
} else if (array_key_exists('skill_name', $_POST)) {
$result = logic_select_has_skill($_POST['skill_name']);
} else if (array_key_exists('worker_id1', $_POST)) {
$result = logic_get_worker_skills($_POST['worker_id1']);
}
echo htmlspecialchars(print_r($result));
}
?>
</body>
my question is that, this code does not validate user input data. I do not know why. Because I did exactly same thing with my other php pages except they only have one form instead of mutiple forms like in case.
as a result, user input does not get validated. $_POST request always get sent to my logic.php.
Hope anyone can help me out.
You should use ID attributes to uniquely identify elements on the page - such as a form in your case.
<form id="myFormID">
<input name="skill_name" type="text" />
</form>
Then you can reference the form via javascript:
document.getElementById("myFormID");
function validate_skill_name()
{
var formElm = document.getElementById("myFormID");
if (formElm.skill_name.value == null || formElm.skill_name.value == "") {
alert("skill name field is incorrect");
formElm.skill_name.focus();
return false;
}
return true;
}
Furthermore, an even better way would be to use jQuery:
$("#myFormID").submit(function(){
var inputElmVal = $("input[name=input_field_name]").val();
if(inputElmVal == '')
{
// Do your null validation here ....
}
});
You need to use value, the name of the input is html element
function validate_skill_name() {
if (document.worker.skill_name.value == null
|| document.worker.skill_name.value == "") {
alert("skill name field is incorrect");
document.worker.skill_name.focus();
return false;
}
return true;
}
http://jsfiddle.net/gcREC/
On a series of web forms users needs to be able to move forwards and backwards. However I want to process the form irrespective of which direction they are going.
The buttonshave name of "submit" and values of "back" and next". How do I interpret the value?
This doesn't work :-)
if(isset($_POST[$submit['back']])) { header('location: ../pages/create_page1.php'); }
if(isset($_POST[$submit['next']])) { header('location: ../pages/create_page3.php'); }
The the name of the field is called submit, so you need to check if the field has been submitted and what its value is:
if ( isset($_POST['submit]') && $_POST[submit] == 'back' )
However you aren't using submit buttons, you are using server side image maps, so the value might not have been submitted (depending on the browser).
Instead you need to give the fields different names, and then check to see if co-ordinates were sent for those fields.
<input type="image" name="submit_back" src="../images/arrows/back_50.png" width="121" height="50" border="0" alt="Back" />
if ( isset($_POST['submit_back_x']) )
Try to use jquery:
$('#some_button').click(funnction(){
var $Data = $('#some-data-input').val();
if($Data.length > 0){ // or some else
window.location.href = "../pages/create_page3.php";
} else {
// other action
}
});
Try this javascript function...
<script language=javascript>
function redirect()
{
if(document.value=="Next")
{
document.form.action="next.php";
}
else if(document.value=="Back")
{
document.form.action="back.php";
}
return true;
}
</script>
<form method="post" name=form onsubmit='return redirect();'>
<p>Click...</p>
<input type="submit" name="back" value="Back"/>
<input type="submit" name="next" value="Next"/>
</form>
You can't get the button value with $submit, it should be $_POST['submit'].
You can try this script.
<?php
if(isset($_POST['next'])) {
$submit = 'Next button was clicked.';
// header(...);
} elseif(isset($_POST['back'])) {
$submit = 'Back button was clicked.';
// header(...);
} else {
$submit = '';
}
?>
<form action="" method="post">
<p>Click...</p>
<input type="submit" name="back" value="Back"/>
<input type="submit" name="next" value="Next"/>
</form>
<br/><?=$submit;?>
Or with same button name and arrows like on your comments:
<?php
if(isset($_POST['submit']) && $_POST['submit'] == 'next') {
$submit = 'Next button was clicked.';
// header(...);
} elseif(isset($_POST['submit']) && $_POST['submit'] == 'back') {
$submit = 'Back button was clicked.';
// header(...);
} else {
$submit = '';
}
?>
<form action="" method="post">
<p>Click...</p>
<input type="image" name="submit" src="http://cdn4.iconfinder.com/data/icons/brightmix/128/monotone_arrow_left_small.png" value="back"/>
<input type="image" name="submit" src="http://cdn4.iconfinder.com/data/icons/brightmix/128/monotone_arrow_right.png" value="next"/>
</form>
<br/><?=$submit;?>