Form submission in php - php

I have a little problem with my if(isset($_POST['submit'])) code. What I want is to run the processForm() function when the submit button for the form has been clicked. The problem is that when I include the if(isset($_POST['submit'])) function, when I click on the submit button the processFunction() does not run at all.but when i include if( !isset($_POST['submit'])) the processForm() function runs... Why is this and can you help me out with this issue please
<html>
<head>
<title>Membership Form</title>
<style type="text/css">
.error { background: #d33; color: white; padding: 0.2em; }
</style>
</head>
<body>
<?php
if ( isset($_POST["submit"])) { //if submit input has value
processForm();//calls the processForm function
}
function processForm(){
$compulsaryForm = array("firstName" , "lastName", "password" , "passwordRetype");
$missingFields = array();
foreach ($compulsaryForm as $input) { //loop
if (!isset($_POST[$input])) {
$missingFields[] = $input;
} // forget the else part cause we mainly want to avoid the warning msg
}
if ($missingFields) {
echo "<p>there are missingFields</p>";
}
}
?>
<form action="htmlForms2.php" method="post">
*name:<input type="text" name="firstName"> <br><br>
*last name: <input type="text" name="lastName"> <br><br>
*password<input type="password" name="password"> <br><br>
*retype password<input type="password" name="passwordRetype"><br><br>
male:<input type="radio" name="sex"><br>
female:<input type="radio" name="sex"><br>
favourite food:<select name = "favourite">
<option value="select">select</option>
<option value="rice">rice</option>
<option value="beans">beans</option>
</select><br>
do you want to recieve news letter?<input type="checkbox" name="newsLetter"><br>
Any comments? :<input type="text" name="comments"><br>
<input type="reset" name="reset">
<input type="submit" name="submit" value="submit">
</form>

your code looks fine in terms of the "submit" field validation. What does not looks fine are these lines:
$compulsaryForm = array("firstName" , "lastName", "password" , "passwordRetype");
$missingFields = array();
foreach ($compulsaryForm as $input) { //loop
if (!isset($_POST[$input])) {
...
All the inputs you're validating against will be sent in the submission, so isset(...) will be true, they may be empty but they will exist for sure. So validate your emptyness on the server side or before sending the form, or even better in both places and it should work ;)
// Use: count($_POST[$input]) < 5, In case you want to validate the text length
if ( !isset($_POST[$input]) || empty($_POST[$input]) || count($_POST[$input]) < 5 {

Related

How to create a cookie to store the timestamp of when a page is first loaded with php

I would really appreciate any help if possible!
This is the question:
Use a cookie (NOT PHP SESSION) that expires a year from now to do the following:
Record the timestamp of the FIRST load of this page (but NOT any subsequent load of this page).
The code:
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h3><?=$message?></h3>
User Profile:
<br><br>
<form action="" method="POST" name="form1" onsubmit="return validate_form()">
<input type="hidden" name="task" value="process_profile">
<input type="checkbox" name="is_cool" value="yes">
Are you cool?
<br><br>
What Bands do you like?
<br>
<select name="like_bands[]" multiple> <small>* Required Field</small>
<option value="Sabbath">Black Sabbath</option>
<option value="Mastodon">Mastodon</option>
<option value="Metallica">Metallica</option>
<option value="Swift">Taylor Swift</option>
</select>
<br><br>
Favorite band not in the above list.
<br>
<input type="text" name="other_band" value="">
<br><br>
<button type="submit"> Continue/Confirm </button>
</form>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client-side form validation
// Don't change the names of stuff in the form, and you won't have to change anything below
// Used built-in JS instead of JQuery or other validation tool
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function validate_form() {
var form_obj = document.form1;
var count_liked = 0;
for (var i=0 ; i < form_obj['like_bands[]'].options.length ; i++ ) {
if (form_obj['like_bands[]'].options[i].selected) {
count_liked++;
}
}
if (count_liked == 0) {
alert("You must choose a band from the menu.");
return false; // cancel form submission
}
return true; // trigger form submission
}
</script>
</body>
</html>
Check if the cookie is already set. If not, set the cookie to the current timestamp.
if (!isset($_COOKIE['load_date'])) {
setcookie('load_date', time(), time() + 86400*365);
}

How to execute a function with an isset under an if statement in PHP

I am making a loan calculator and I want to run some calculations that are being posted from a form using the POST method. The code is not executing when I run it. Where am I am missing it?
I have run the code without the function and it seems to be working well, but the moment I put it in a function its not running.
function loancal()
{
if(isset($_POST['submit'])) {
$principal = $_POST['principal'];
$intrstRate = $_POST['intrest'];
$tenure = $_POST['tenure'];
$result = ($principal * $intrstRate * $tenure) ;
echo $result;
} else {
echo '00.00';
}
}
This is the line that is calling the function after it has been submitted:
<h1 class="title is-2"> $<?php loancal(); ?></h1>
I am expecting the out to change from $00.00 to for example a calculated result, but the output is still the same $00.00
This is the form (excerpt).
<form method="post" action="">
<input type="text" name="principal">
<input type="text" name="intrest">
<input type="date">
<input type="text" name="tenure">
<button type="submit">Calculate</button>
<button type="reset" >Clear</button>
</form>
So my very first answer is your issue, you need to give your submit button a name.
<button name="submit" class="button is-rounded is-primary" type="submit">Calculate</button>
Here's one way to get the code to execute:
<?php
function loancalc() {
$result = '0.00';
if( isset( $_POST['submit'] )){
// inspecting submitted values so that...
foreach ($_POST as $key => $value){
$bool[$key] = ctype_print( $value );
}
// ... if proven valid, then make assignments
if ( $bool['principal'] && $bool['interest'] && $bool['tenure'] ) {
// array destructuring available since PHP 7.1
[$principal, $interestRate,$tenure] =
[$_POST['principal'],
$_POST['interest'],
$_POST['tenure']];
$result = $principal * $interestRate * $tenure;
} // inner if
} // if POSTed
echo number_format( $result,2,'.',',' ); // default English representation
} // end func
?>
<html>
<head>
<title>Untitled</title>
<style>
#submit {
background: #000;
color: lime;
}
#clear {
background: #000;
color: cyan;
}
input {
background: #ffffee;
color: #303;
}
h1 {
font-size: 32pt;
margin-bottom: 3em;
color: #f0c;
}
</style>
</head>
<body>
<h1>$
<?php loancal(); ?>
</h1>
<form method="post" action="">
<input type="text" name="principal" id="principal">
<input type="text" name="intrest" id="intrest">
<input type="date">
<input type="text" name="tenure" id="principal">
<button type="submit" name="submit" id="submit">Calculate</button>
<button type="reset" id="clear">Clear</button>
</form>
</body>
</html>
The form values will only be properly submitted if they possess name attributes. Id attributes are optional and handy for front-end code manipulation.
Important point: Be sure to treat user submitted data as suspect, i.e. possibly tainted. In this example, a simple check makes sure that the the user input values only contain printable characters.
(Related demo of PHP code here.)
Refinements:
gave $result default value and eliminated an if-else clause
formatted the number with number_format() to make the number more user-friendly.
added some styling for fun :)

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

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!

Pause form from submitting with javascript

I am trying to do a submit form with photos. After the user loads the photos he presses the submit button, I want the form to pause for 10 seconds, animate a progress bar for those 10 seconds and then submit the form, can you guys say what I did wrong, it doesn't seem to submit the form after 10 seconds.
Here is the code:
HTML:
<form action="uploadpic.php" method="post" id="upload_form">
<input type="text" name="title" id="title">
<p id="title_p">Title</p>
<hr />
<input type="text" name="theme" id="picture_theme" size="40"/>
<p id="theme">Picture Theme<img src="../simages/info.gif" id="info" width="12" height="12" style="margin-left:10px;"></p>
<hr />
<div class="custom-upload">
<input type="file" name="picture" id="true_pic" />
<div class="fake-file">
<input disabled="disabled" >
</div>
</div>
<p id="upload_pic">Upload picture</p>​
<input type="submit" name="submit" id="submit" value="Upload" />
</form>
JAVASCRIPT:
form = document.getElementById("upload_form");
size=1;
form.onsubmit = function()
{
if (size < 10)
{
setTimeout(delayedSubmit,1000);
}
return false;
}
function delayedSubmit() {
size++;
if (size<5)
{
setTimeout(delayedSubmit,1000);
alert("Counting "+size);
}
else
{
alert("Form submitted");
form.submit();
}
}
PHP :
<?php
if ($_POST['submit'])
{
$title = $_POST['title'];
$theme = $_POST['picture_theme'];
echo $title," ",$theme;
}
?>
I can tell that the form won't submit anything by the fact that the php variables won't show anything, and then page doesn't load.
When a form has a button with the name and/or id "submit", it won't work anymore (my old post was wrong).
So what you need to do is to change the name/id of the button:
<input type="submit" name="submit-button" id="submit-button" value="Upload" />
Remember: You need to change your PHP, too:
if ($_POST['submit'])
{
$title = $_POST['title'];
$theme = $_POST['picture_theme'];
echo $title," ",$theme;
}
to
if ($_POST['submit-button'])
{
$title = $_POST['title'];
$theme = $_POST['picture_theme'];
echo $title," ",$theme;
}
I'd simplify the javascript:
form = document.getElementById("upload_form");
size=0;
form.onsubmit = delayedSubmit;
function delayedSubmit () {
if (++size < 5) {
alert("Counting "+size);
setTimeout(delayedSubmit,1000);
return false;
}
alert("Form submitted");
form.submit();
}
And - of course - remove (or change) id and name from the submit button, e.g:
<input type="submit" value="Upload" />
e.g.: http://jsbin.com/equyit/1/edit

Categories