PHP not executing after try block - php

I have created a demo calculator which works perfect except one time when the form gets submitted it goes inside try block and the rest html page doesn't get displayed.. am i doing it wrong? i dont see any reason why it shouldn't execute the rest of the code
I very well understand the try catch finally concept but cant see where's the error
this is my class.calculator.php
class NoNumberProvided_Exception extends Exception {}
class Calculator {
function __construct() {
$args = func_get_args();
if(!$args) {
throw new NoNumberProvided_Exception("Please provide atleast 2 numbers");
} else {
if($args[0] && $args[1]) {
if($args[2] == "Add") {
echo $args[0]+$args[1];
} else if($args[2] == "Divide") {
echo $args[0]/$args[1];
} else if($args[2] == "Subtract") {
echo $args[0]-$args[1];
} else if($args[2] == "Multiply") {
echo $args[0]*$args[1];
}
} else {
throw new NoNumberProvided_Exception("Please provide atleast 2 numbers");
}
}
}
}
PHP:
if(isset($_POST['submit'])) {
include 'class.calculator.php';
try {
$num = new Calculator($_POST['number1'], $_POST['number2'], $_POST['submit']);
echo $num; // after the form gets submitted, this gets echoed but the html form below doesnt show on the page
} catch (NoNumberProvided_Exception $nonumber) {
echo $nonumber->getMessage();
}
}
HTML:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Number1: <input type="text" name="number1" id="number1" />
<br/>
Number2: <input type="text" name="number2" id="number2" />
<br/><br/>
<input type="submit" id="submit" name="submit" value="Add" />
<input type="submit" id="submit" name="submit" value="Divide" />
<input type="submit" id="submit" name="submit" value="Subtract" />
<input type="submit" id="submit" name="submit" value="Multiply" />
</form>

The reason you are not seeing the HTML content after echo $num is because you are getting a fatal error.
This is seen when running your code in a php console (php -a)
php > $num = new Calculator(1,2,'Subtract');
-1
php > echo $num;
PHP Catchable fatal error: Object of class Calculator could not be converted to string in php shell code on line 1
PHP Stack trace:
PHP 1. {main}() php shell code:0
php >
To address this problem, we could make a few conceptual changes to your Calculator class:
A method should only do One Thing. A constructor is best used for initialization, and your calculator's functions Add, Subtract, Multiply, and Divide probably should be separate methods.
As a general rule, an object (being a part of the model, or logic section), should never echo or print its result. This is, in my opinion, a merging of logic and presentation-- which you should strive to separate. It's also part of the problem you ran into.
My first inclination would be to pass the parameters into the methods, instead of the constructor. This allows you to type hint the values you expect. I'm showing integer as example. If bad data (string) is passed, it will throw an exception. If only 1 value is passed, it will throw an exception.
At the end of the day, there's no one "right" way to do it; experience helps show ways that will be easier to work on later. :)
My suggestions, FWIW...
Class:
<?php
class Calculator {
public function __construct() { }
public function add(int $addend1, int $addend2) {
return $addend1 + $addend2;
}
public function subtract(int $subtrahend, int $minuend) {
return $subtrahend - $minuend;
}
public function multiply(int $factor1, int $factor2) {
return $factor1 * $factor2;
}
public function divide(int $dividend, int $divisor) {
return $dividend / $divisor;
}
}
PHP / HTML
function assignPostVar($name) {
if(isset($_POST[$name])) {
return $_POST[$name];
}
}
$error = '';
if(isset($_POST['submit'])) {
$calc = new Calculator;
$n1 = assignPostVar('number1');
$n2 = assignPostVar('number2');
try {
switch($_POST['submit']) {
case 'Add':
$result = $calc->add($n1,$n2);
break;
case 'Subtract':
$result = $calc->subtract($n1,$n2);
break;
case 'Multiply':
$result = $calc->multiply($n1,$n2);
break;
case 'Divide':
$result = $calc->divide($n1,$n2);
break;
default:
throw new Exception('Invalid operation');
}
} catch (Exception $e) {
$error = $e->getMessage();
}
}
?>
<?php if($error): ?>
<div class="error">Encountered error: <?= $error ?></div>
<?php endif; ?>
<form method="POST">
Number1: <input type="text" name="number1" id="number1" />
<br/>
Number2: <input type="text" name="number2" id="number2" />
<br/><br/>
<input type="submit" id="add" name="submit" value="Add" />
<input type="submit" id="divide" name="submit" value="Divide" />
<input type="submit" id="subtract" name="submit" value="Subtract" />
<input type="submit" id="multiply" name="submit" value="Multiply" />
</form>

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 My code doesn't send to the right page after using edit button

I have the following problem. I created a .php file that creates(extends) two new pages. In the first page there is a button called submit which after click on it send me to the next page called editname. When I made click on the button (edit)of the second page, it send me to the third page called recorndname. In the third page, there are two buttons called update and delete which send me to the second page. But, actually it is working as it should. Here is part of my code.
//here is my main class
class main {
public function __construct() {
$page_request = 'homepage';
if(isset($_REQUEST['page'])) {
$page_request = $_REQUEST['page'];
}
$page = new $page_request;
if($_SERVER['REQUEST_METHOD'] == 'GET') {
$page->get();
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST'){
$page->post();
} else{
$page->delete();
}
}
}
Here is my page class. In this part seems neither one of the functions are called.
//Page class
class page {
public function get() {
echo 'I am a get method page';
}
public function post() {
echo 'I am a post method';
$user=new users();
//$user->addUser($_POST["firstname"],$_POST["lastname"],$_POST["email"]);
if($_POST['botton'] == 'Submit'){
$user->addUser($_POST["firstname"],$_POST["lastname"],$_POST["email"]);
} else if($_POST['botton'] == 'Update'){
$user->update($_POST["email"],$_POST["firstname"],$_POST["lastname"]);
} else if($_POST['botton'] == 'Delete'){
$user->deleteUser($_POST["email"]);
}
}
public function delete(){
echo 'I am a delete method';
}
}
Here are my extended pages.
//Page classes
class homepage extends page {
public function get() {
echo 'homepage';
echo'<form action="projectBackup.php?page=editname" method="post">
First name:<br>
<input type="text" name="firstname" value="">
<br>
Last name:<br>
<input type="text" name="lastname" value="">
<br>
Email Address:<br>
<input type="text" name="email" value="">
<br><br>
<input type="submit" name="button" value="Submit">
</form>';
}
}
class editname extends page {
public function post(){
echo 'editname';
$users=new users();
$userlist=$users->listUsers();
echo '<table><tr><th>First Name</th><th>Last Name</th><th>Email Address</th></tr>';
foreach($userlist as $Kuser=>$user){
echo '<tr><td>'.$user['fname'].'</td><td>'.$user['lname'].'</td><td>'.$Kuser.'</td><td>';
echo '<form action="projectBackup.php?page=recordname" method="get">
<input type="hidden" name="email" value="$Kuser">
<input type="submit" value="Edit"></form>';
}
echo '</table>';
}
}
class recordname extends page {
public function get() {
echo 'recordname';
$users=new users();
$userlist=$users->listUsers();
echo'<form action="projectBackup.php?page=editname" method="post">
First name:<br>
<input type="text" name="firstname" value="$userlist[$_GET["email"]["fname"]">
<br>
Last name:<br>
<input type="text name="lastname" value="$userlist[$_GET["email"]["lname"]">
<br>
Email Address:<br>
<input type="text" name="email" value="$_GET["email"]">
<br><br>
<input type="submit" name="button" value="Update">
<input type="submit" name="button" value="Delete">
</form>';
}
}
Can someone help me with this? Thank you in advance.

Can't get values from textbox to class

I want to make a basic calculator. Every thing is set, the textboxes and buttons. It needs to be OOP, but that gives me problems. It worked before until I tried to do it in OOP.
I don't get errors but when ever I try to let the code calculate a sum, it results the answer as 0. Its probably because the class doesn't get the values from the textboxes, but I don't know how to fix it.
Code of the class where the calculation needs to be:
class CountUp
{
public static $_sum;
public static $number1;
public static $number2;
public function __construct()
{
self::$_sum;
self::$number1;
self::$number2;
}
public function getnumber1()
{
self::$number1 = ($_POST['number1']);
return self::$number1;
}
public function getnumber2()
{
self::$number2 = ($_POST['number2']);
return self::$number2;
}
public static function getsum()
{
$_sum = self::$number1 + self::$number2;
return $_sum;
}
}
Sorry if this is a stupid question, I'm bad at php.
EDIT: This is where the values are supossed the come from:
<html>
<head>
</head>
<body>
<form name ="btw calculate" method="post" action="test2.php"><br/>
enter a number <br/>
<input type="tekst" name="number1" value=""><br/>
<input type="submit" name="plus" value="+">
<input type="submit" name="retract" value="- "><br/>
<input type="submit" name="divide" value="/ ">
<input type="submit" name="multiply" value="* "><br/>
enter a second number <br/>
<input type="tekst" name="number2" value=""><br/>
</form>
</body>
</html>
EDIT2: I'm an idiot, forgot to add this part to this question:
<?php
include("plus.class.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['plus']))
{
echo CountUp::getSum();
}
else
{
//still empty for now
}
}
?>
You are mixing up static functions which are related to the class definition.
And object instance functions, which are related to each 'new' 'instance' of a class you create.
Here in an input form and the class adding the $_POST array values together.
<?php if (!empty($_POST['number1'])) {
// object instance version
class CountUp
{
private $number1 = 0;
private $number2 = 0;
public function setNumber1($number)
{
$this->number1 = $number;
}
public function setNumber2($number)
{
$this->number2 = ($number)
public function getSum()
{
$_sum = $this->number1 + $this->number2;
return $_sum;
}
}
$addTwoNumbers1 = new CountUp();
$addTwoNumbers1->setNumber1($_POST['number1']);
$addTwoNumbers1->setNumber2($_POST['number2']);
?>
<p> The answer of: <?= $_POST['number1']?> + <?= $_POST['number2'] ?> = <?= $addTwoNumbers1->getSum(); ?>
<?php
}
?>
<html>
<head>
</head>
<body>
<form name ="btw calculate" method="post" action=""><br/>
enter a number <br/>
<input type="text" name="number1" value=""><br/>
<p>will be added to...</p>
enter a second number <br/>
<input type="text" name="number2" value=""><br/>
<input type="submit" name="plus" value="add the two numbers together...">
</form>
</body>
</html>

how to call php function from submit button?

my filename is contacts.php that have two submit buttons;i want that if insert button is pressed insert function is called and if select is pressed select is called.i have written following code:
//contacts.php
<?php
if(isset($_REQUEST['select']))
{
select();
}
else
{
insert();
}
?>
<html>
<body>
<form action="contacts.php">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select()
{
//do something
}
function insert()
{
//do something
}
?>
but it is not working .please help
<?php
if (isset($_REQUEST['insert'])) {
insert();
} elseif (isset($_REQUEST['select'])) {
select();
}
Your code is calling insert() even if no button is clicked, which will happen when the page is first displayed.
use post method because it is secure
//contacts.php
<?php
if(isset($_POST['select']))
{
select();
}
else
{
insert();
}
?>
<html>
<body>
<form action="contacts.php" method="post">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select()
{
//do something
}
function insert()
{
//do something
}
?>
If you are using return inside function to return the result , you have to use echo to print the result while calling function.
if(isset($_REQUEST['select']))
{
echo select();
}
elseif(isset($_REQUEST['insert']))
{
echo insert();
}
As has been described by several people (summarizing the previous comments), you have two options.
The first is to send the data via POST or GET to the server directly and reserve (refresh) the page based on whatever you do inside select() and insert().
While this is not the right place for a POST v GET discussion, convention is to use POST when sending data to the server. POST is slightly more secure because the information is not stored in the browser. Read more about the two here: http://www.w3schools.com/tags/ref_httpmethods.asp
The second option is to use AJAX to accomplish your task without refreshing the web page. In short, AJAX uses Javascript methods that you place on your page to communicate with your server, thus avoiding the need for the PHP on the server to actually change anything on the page (which would require a refresh). A code example of AJAX can be found here: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
<?php
$insert = $_POST['insert'];
$select = $_POST['select'];
if ($insert) {
insert();
}
if ($select) {
select();
}
else {
echo 'press any button...';
}
?>
<html>
<body>
<form action="contacts.php" method="post">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select() {
echo 'you pressed the [select] button';
exit;
}
function insert() {
echo 'you pressed the [insert] button';
exit;
}
?>

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!

Categories