javascript does not validate multiple forms in a single php page - php

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/

Related

How do i clear this array by user input in php/html?

I am working on a program that has the user type in their course, first name, last name, and description of a program. The code is mostly done except for getting the clear the array button to work. When I use the unset array to clear the array on its own, it works but then the user cant enter in more data. I want to have the user be able to clear the data. Here is my code:
<?php
session_start();
?>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "gethint.php?q="+str, true);
xmlhttp.send();
}
}
</script>
<?php
function clear(){ //this is the problem
unset($_SESSION['courses']);
return true;
}
?>
</head>
<body>
<form method="POST">
Course: <input type="text" name="courses" />
<br /><br />
First Name: <input type="text" name="firstname" />
<br /><br />
Last Name: <input type="text" name="lastname" />
<br /><br />
Description: <input type="text" name="description" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<?php
// First we check if the form has been sent and we have a value
if (!empty($_POST['courses'])) {
if (!isset($_SESSION['courses']))
$_SESSION['courses'] = array(); // Initialize the array if it doesn't exist
// Add the value to our array
$_SESSION['courses'][] = array("course" => $_POST['courses'],
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"description" => $_POST['description']);
}
// If there are values to show, print them!
if (!empty($_SESSION['courses'])) {
foreach ($_SESSION['courses'] as $course) {
echo $course['course']." ".
$course['firstname']." ".
$course['lastname']." ".
$course['description']." ".
"<br />";
}
}
?>
<input type="submit" name="Clear" value="Clear" onclick="clear()"> //this is the problem
<?php
?>
</body>
</html>
Can someone please help?
<?php
// there is nothing wrong with this function.
function clear() {
unset($_SESSION['courses']);
return true;
}
?>
Okay, this function is fine, there is nothing wrong with it. But, you can't use this function like:
<input type="submit" name="Clear" onclick="Clear()" /> <!-- this is the problem -->
You see that onclick="Clear()", and that php function clear()? Yeah, you can't execute php functions with a html onclick="". You can only do that with javascript functions.
But you can do something like this:
<?php
if(isset($_POST['Clear']))
{
// if the user submits the form, then the following code will be executed.
clear();
}
?>
<input type="submit" name="Clear" value="Clear" onclick="clear()">
clear() would be calling a javascript function. You have correctly written a php function.
Check the value of the submit button "Clear" to be "clear" and if true run the PHP function clear().
if ($_POST['Clear'] === 'clear') {
clear();
}

PHP form error logic

Normally when we submit form in php and show errors then the errors are posted in other page.
Now my question is.
If we want to show the errors on same page mean on the form page, then how to do it?
I used session for that and found it better then other process but when I want to show all session variable at once then it will not show, why?
My code is:
if(isset($_POST) && count($_POST)>0) {
$user =test_input($_POST['user']);
$pass = test_input($_POST['pass']);
$securepassword=hash('sha512', $pass);
if(empty($user)&&empty($pass))
{
echo 'fill every field';
}
else if(empty($user)||empty($pass))
{
echo 'fill both the field';
}
else
{
$sSQL = "SELECT * FROM signup WHERE Username ='".$user."' AND Password = '".$securepassword."'";
$result = mysql_query($sSQL) or die(mysql_error());
$row=mysql_num_rows($result);
if($row==1)
{
// Set username session variable
$_SESSION['user'] = $user;
// Jump to secured page
header('location:index.php');
}
else
{
header('location:signin.php');
}
}
}
You better use JavaScript for validating the form. Lets say this is your HTML code.
<form method="post" name="loginForm" action="abc.php">
<input type="text" name="user">
<input type="password" name="pass">
</form>
Now, let’s add validate this form before you POST to abc.php:
<form method="post" name="loginForm" action="abc.php" onsubmit="return validater()">
<input type="text" name="user">
<input type="password" name="pass">
</form>
And the JavaScript is:
function validater() {
var a= document.forms["loginForm"]["user"].value;
if (a==null || a=="") {
alert("Fill out the username");
return false;
}
var b= document.forms["loginForm"]["pass"].value;
if (b==null || b=="") {
alert("Enter your password");
return false;
}
}
Logic is simple you can put the php code and html code on the same page. In the following order.
Put your php validation code.
Put your error code to show errors above the form.
Put your html code to show the form fields on the page.
There is no need of session to show errors to the user.

Registration Validation in PHP, with Javascript alert boxes

I wanted to create a registration validation system (to make sure that the user registered has valid info) with PHP and Javascript Alert Boxes. Each time a user does not do a field correctly, I want him to get an alert box saying that it is incorrect. So here it is:
Code #1 - For generating alerts in PHP (This is for the event in the button).
function alert($string)
{
echo "javascript:alert('$string');";
}
Code #2 - PHP placed inside the onclick="" attribute for the submit button.
if (!isset($fname) || empty($fname))
{
alert('Please enter your first name!');
}
elseif (!isset($lname) || empty($lname))
{
alert('Please enter your last name!');
}
elseif (!isset($gender) || empty($gender))
{
alert('Please specify your gender!');
}
elseif (!isset($phone) || empty($phone) || strlen($phone) != 10)
{
alert('Please enter your correct Phone Number!');
}
elseif (!isset($user) || empty($user) || strlen($user) > 10 || strlen($user) < 5)
{
alert('Please enter a Username that is 5-10 characters long!');
}
elseif (!isset($pass) || empty($pass) || strlen($pass) > 10 || strlen($pass) < 5)
{
alert('Please enter a Password that is 5-10 characters long!');
}
elseif (!isset($repass) || empty($repass) || $pass != $repass)
{
alert('Please repeat your Password');
}
else
{
$query = mysql_query($query_send_form);
query_error($query);
}
As you have probably realised, the variables are actually equal to the $_POST values of the field in the form.
So the problem is that the onclick of the button is ALWAYS equal to onclick="
javascript:alert('Please enter your first name!');" It wouldn't change.
Please don't give me a complete javascript alternative to the system, I want to learn PHP for now.
Thanks for your help in advance.
EDIT #1
An important thing I forgot to mention was that the form target is just an iframe on the same page, so that the content the user has entered stays while he is being shown the error.
<form method="post" target="frame" action="register.php">
register.php is the same page where the form HTML and the validation PHP is.
EDIT #2
The data is being posted. Here are the declared varibles:
#$fname = $_POST['fname'];
#$lname = $_POST['lname'];
#$gender = $_POST['gender'];
#$phone = $_POST['phone'];
#$user = $_POST['user'];
#$pass = $_POST['pass'];
#$repass = $_POST['repass'];
You really shouldn't do that kind of validation like that...
Anytime you want to tell the user something is invalid because of logic rules, it is done with javascript on the front side. There are some good plugins out there written in either jquery or javascript out here. You can also make something simple on your own. This helps the user because then they don't have to submit the page to find out that their password isn't long enough.
You still need to do validation after POST and before putting things in the database because of sql injection. That kind of validation is a little different because you're just looking for things that are harmful.
This example is self-contained. The messages go to a div instead of alerts.
<?php
$message = "";
$submit = (isset($_POST['submit'])) ? $_POST['submit'] : '';
if (!empty($submit)) {
$message = "thanks for submitting the form!";
}
?><div id="errors"><?php echo $message ?></div>
<form id="my_form" name="my_form" action="" method="post">
<div style="display:inline-block;">Name<br/>
<input name="first_name" type="text" size=8 class="required"/>
<input name="last_name" type="text" size=16 class="required"/>
</div>
<div style="display:inline-block;">Gender<br/>
<select name="gender" class="required">
<option value=''></option>
<option value='M'>M</option>
<option value='F'>F</option>
</select>
</div>
<div style="display:inline-block;">Phone Number<br/><input name="phone" type="text" class="required"/></div><br/>
<div style="display:inline-block;">Username<br/><input name="username" type="text" class="required"/></div><br/>
<div style="display:inline-block;">Password<br/><input name="password" type="password" class="required"/></div>
<div style="display:inline-block;">Repeat Password<br/><input name="repeat_password" type="password" class="required"/></div><br/>
<div style="display:inline-block;">Description<br/><textarea name="description"></textarea></div><br/>
<button type="submit">Submit</button>
<input type="hidden" name="submit" value="submit"/>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<style> .invalid {border-color:red}</style>
<script>
$(document).ready(function(){
$("#my_form").submit(function(e){
var messages = perform_validation();
if (messages.length!==0) {
$("#errors").empty();
$.each(messages,function(i,msg){
$("#errors").append(msg+"<br/>");
});
e.preventDefault();
return false;
}
// else continue to submit form normally
});
function perform_validation()
{
var messages = [];
$("#my_form :input.required").removeClass("invalid");
$("#my_form :input.required").each(function(){
if ($(this).val().length===0) {
$(this).addClass("invalid");
var name = $(this).attr('name').replace('_',' ');
messages.push("Please provide a "+name+".");
}
});
var password = $("input[name='password']").val();
if (!(password.length>=5 && password.length<=10)) {
messages.push("Password length must be between 5 and 10 characters.");
}
else {
if (password!=$("input[name='repeat_password']").val()) {
messages.push("Repeat password doesn't match first password.");
}
}
return messages;
}
});
</script>
Unless you have magic quotes turned on (and I hope you don't), your values such as $fname will always be undefined. You probably want to replace those with $_POST['fname'].
On a side note, you can use just empty() without !isset() since empty() will return FALSE if the value is not set.

return true for same page validation

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!

multiple button with one onsubmit

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'];
}
}
}
?>

Categories