PHP - multiple forms, get values from both upon submit? - php

I am a little stuck at the moment and could use some help please.
I have a calendar which is being used by multiple departments to enter their schedule in. Each user is asked to complete 1x select and 2x input fields which are divided into FORM 1 and FORM 2
FORM 1:
department code (onclick submit event)
FORM 2:
name
date
submit button
After the user has selected his/her department code, the calendar will refresh and fetch the entries for this specific department only (meaning it will filter all records for the department code). After that, the user has to enter his username and select a date, followed by pressing the submit button (form 2).
Now, the problem is that in order for FORM 2 to submit correctly, I need to know the department code from Form 1. Additionally, I am having troubles preventing the calendar from refreshing (Form 1) when pressing the submit button for Form 2.
In short, how can I clearly distinguish the ($_POST) between form 1 and form 2, while accessing both form's data?
PHP
<?php
// SHOULD BE EXECUTED AFTER THE SUBMIT BUTTON WAS CLICKED
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['type']) && ($_POST['type']=='new_entry')) {
// include connection details
include '../../plugins/MySQL/connect_db.php';
// Open a new connection to the MySQL server
$con = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
// Output any connection error
if ($con->connect_error) {
die('Error : ('. $con->connect_errno .') '. $con->connect_error);
}
// define variables
$table = 'calendar';
$type = mysqli_real_escape_string($con,$_POST['type']);
$holidex = mysqli_real_escape_string($con,$_POST['holidex']);
if($type == 'new_entry')
{
// define variables and query
$mod_property = mysqli_real_escape_string($con,$_POST['holidex']);
$mod_name = mysqli_real_escape_string($con,$_POST['mod_name']);
$mod_date = date('Y-m-d',strtotime($_POST['mod_date']));
$sql = "INSERT INTO calendar (`title`, `startdate`, `enddate`, `allDay`, `color`, `holidex`) VALUES ('$mod_name','$mod_date','$mod_date','true','','$mod_property')";
print($sql);
$result = $con->query($sql) or die('<p>Could not submit new MOD record into database: ' . MYSQLI_ERROR() . '</p>');
$result->free();
}
$con->close();
}
?>
<form name="form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<!-- <form name="mod_form" action="../../plugins/MySQL/ajax_action.php?type=new_entry" method="POST"> -->
<!-- Property -->
<div class="col-md-4">
<label>Property</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-server"></i></span>
<select name="holidex" id="holidex" class="form-control select2" style="width: 100%;" data-placeholder="Select your property" onchange="this.form.submit();" method="POST" <?php if($_SESSION['Access']=='User') { echo "disabled"; } ?>>
// get all my departments and their respective codes
<option value="1">Dept. 1</option>
<option value="2">Dept. 2</option>
<option value="3">Dept. 3</option>
</select>
</div>
<!-- /btn-group -->
</div>
<!-- /.property -->
</form>
<form name="form2" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<!-- MOD Name -->
<div class="col-md-4">
<label>MOD Name</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<select name="mod_name" id="mod_name" class="form-control select2" style="width: 100%;" data-placeholder="Select a name">
<option value=""></option>
<option value="1">User1</option>
<option value="2">User2</option>
<option value="3">User3</option>
</select>
</div>
<!-- /.input-group -->
</div>
<!-- /.mod name -->
<!-- MOD Date -->
<div class="col-md-3">
<label>MOD Date</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-server"></i></span>
<input type="date" class="form-control" name="daterangepicker" id="daterangepicker" />
<!-- <input type="date" id="mod_date" name="mod_date" class="form-control" style="width: 100%;"> -->
</div>
</div>
<!-- /.mod date -->
// hidden input field to determine the type and help differentiate the $_POST submissions
<input type="hidden" class="form-control" name="type" id="type" value="new_entry"/>
<!-- Submit button -->
<div class="col-md-1 text-center">
<label> </label>
<button type="submit" name="btnSubmit" class="btn btn-primary btn-block" onclick="this.disabled=true; this.value = 'Wait...'; this.form.submit(); return true;">Submit</button>
</div>
<!-- /.submit button -->
</form>
<!-- /.form 2 -->

Following SiteThief's suggestion, I am skipping the <form> approach altogether and am submitting the results via AJAX to my php handler file. Works like a charm without the pesky form submission problems.
JS
<script>
// SAVE NEW DEPARTMENT RECORD - SAVE BUTTON
$("#SubmitButton").click(function() {
// check that input fields are not empty
if($("#holidex").val()!="" && $("#mod_name").val()!="" && $("#mod_date").val()!="") {
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"mod_calendar",type:"new_entry",holidex:$("#holidex").val(),mod_name:$("#mod_name").val(),mod_date:$("#mod_date").val()},
dataType: "html",
success: function(data) {
$('#mod_output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
alert("Please choose a hotel, staff name and MOD date from the list.");
return;
}
// close modal and refresh page
setTimeout(function(){location.reload()}, 1000);
return;
});
</script>

Related

How to save to database MySQL/MariaDB using PHP-JQuery?

I want to create a simple website to show form input fields based on select values. Here is my codes:
index.php
<?php
include('conn.php');
?>
<!-- For server type field -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
// For physical type -------------------------------------
$(document).ready(function () {
toggleFieldsPhys(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#type").change(function () {
toggleFieldsPhys();
});
});
// this toggles the visibility of other server
function toggleFieldsPhys() {
if ($("#type").val() === "physical")
$("#physical").show();
else
$("#physical").hide();
}
// -------------------------------------------------------
// For cloud type ----------------------------------------
$(document).ready(function () {
toggleFieldsCloud(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#type").change(function () {
toggleFieldsCloud();
});
});
function toggleFieldsCloud() {
if ($("#type").val() === "vps")
$("#vps").show();
else
$("#vps").hide();
}
// -------------------------------------------------------
</script>
<body>
<center>
<h1>Add Server</h1>
<center>
<form method="POST" action="add_process.php" enctype="multipart/form-data" >
<section class="base">
<div>
<label>Server Type</label>
<td>
<select id="type" name="type" required>
<option value="">Choose Type</option>
<option value="physical">Physical</option>
<option value="vps">VPS Hosting</option>
</select>
</td>
</div>
<div class="input-group" id="physical">
<fieldset>
<p>Server Name:
<input type="text" name="servername" required />
</p>
<p>Manufactur:
<input type="text" name="brand" required />
</p>
<p>Type:
<input type="text" name="product" required />
</p>
<p>Serial Number:
<input type="text" name="sn" required />
</p>
</fieldset>
</div>
<br>
<div class="input-group" id="vps">
<fieldset>
<p>Hosting Name
<input type="text" name="hosting" required />
</p>
</fieldset>
</div>
<br>
<div>
<label>Processor</label>
<input type="text" name="processor" autofocus="" required="" />
</div>
<br>
<br>
<div>
<button type="submit">Save</button>
</div>
</section>
</form>
</body>
</html>
add_process.php
<?php
include 'conn.php';
$type = $_POST['type'];
$number = $_POST['number'];
$servername = $_POST['servername'];
$brand = $_POST['brand'];
$product = $_POST['product'];
$sn = $_POST['sn'];
$hosting = $_POST['hosting'];
$processor = $_POST['processor'];
$query = "INSERT INTO try (type, number, servername, brand, product, sn, hosting, processor ) VALUES ('$type', '$number', '$servername', '$brand', '$product', '$sn', '$hosting', '$processor')";
$result = mysqli_query($conn, $query);
if(!$result){
die ("Query Failed: ".mysqli_errno($conn).
" - ".mysqli_error($conn));
} else {
echo "<script>alert('Data Saved');window.location='index.php';</script>";
}
The problem is when I choose Physical type, the data is saved to the database. But when I choose VPS Hosting, I cannot Save to the database because the save button can't be clicked normally.
What should I do if I click VPS Hosting and I fill the form, the data save to the database?

Keep the form open when sending data to the table

I have this code with multiple forms within the same page:
test1 page:
<select id="mudar_produto">
<option value="#produto_1">Novo Produto Higiene</option>
<option value="#produto_2">Entrada de Produtos Higiene</option>
<option value="#produto_3">Novo Produto Nutricia</option>
</select>
<section class="hide-section" id="produto_1">
<form id="form3" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="DescricaoProd" name="DescricaoProd" required="" style="width:350px">
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<input type="text" id="DescricaoUnid" name="DescricaoUnid" style="width:160px" required="" size="120">
</div>
</fieldset>
<button type="submit" name="submit" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_2">
<form name="form4" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Entrada de Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Data Entrada">Data Entrada</label></strong>
<input id="DataEntrada" type="date" name="DataEntrada" required="" style="width:180px" value="<?php echo date("Y-m-d");?>">
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Produto">Produto</label></strong>
<select id="first_dd" name="Produto" style="width:250px" required>
<option></option>
<?php
$sql = "SELECT * FROM centrodb.ProdHigieneteste WHERE Ativo = 1 ORDER BY DescricaoProd ASC";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['IDProd'].'"> '.$ln['DescricaoProd'].'</option>';
$valencia[$ln['IDProd']]=array('DescricaoUnid'=>$ln['DescricaoUnid'],'DescricaoUnid'=>$ln['DescricaoUnid']);
}
?>
</select>
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<select id="second_dd" name="Unid" style="width:150px" required>
<option></option>
<?php
foreach ($valencia as $key => $value) {
echo '<option data-id="'.$key.'" value="'.$value['DescricaoUnid'].'">'.$value['DescricaoUnid'].'</option>';
}
?>
</select><br>
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Quantidade">Quantidade</label></strong>
<input type="text" id="Quantidade" name="Quantidade" style="width:80px" required="" size="40">
</div>
<div class="campo">
<strong><label for="Preço">Preço</label></strong>
<input type="text" id="Preco" name="Preco" style="width:100px" value="0.00">
</div>
</fieldset>
<button type="submit" name="submit1" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_3">
<form id="form3" name="form3" action="./teste2" method="POST" onsubmit="return form_validation()" >
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Nutricia</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="ProdNutricia" name="ProdNutricia" style="width:350px" required="" size="120" />
</div>
</fieldset>
<button type="submit" name="submit2" class="botao submit">Registo</button>
</form>
</section>
In the page teste2 I make the insertion of the data in the table of the database:
<script language="javascript" type="text/javascript">
document.location = "teste1";
</script>
<?php
if(isset($_POST['submit'])){
$name = $_POST['DescricaoProd'];
$unid = $_POST['DescricaoUnid'];
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit1'])){
$data = $_POST['DataEntrada'];
$produto = $_POST['Produto'];
$unidade = $_POST['Unid'];
$quantidade = $_POST['Quantidade'];
$preco = $_POST['Preco'];
$sql = "INSERT INTO regEntradahigieneteste (DataEntrada,Produto,Unid,Quantidade,Preco)
VALUES ('$data','$produto','$unidade','$quantidade','$preco')";
if ($conn->query($sql) === TRUE);
$sql1 = "UPDATE StockHigieneteste SET Quantidade = Quantidade +" . $quantidade . " WHERE StockHigieneteste.IDProd =" . $produto;
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit2'])){
$name = $_POST['ProdNutricia'];
$sql = "INSERT INTO ProdNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
Everything is working correctly with the insertion of data in the table, but when I do the insertion and does the header ("Location: teste1"); closes the form I was filling out and I want to keep it open, since I may have to insert several types of products on the same form.
Some explanation to start with:
I have cleaned up your HTML markup. You may have gotten the look you desired, but the markup is badly broken. A good editor will help you with making a well-formed document that validates.
I've used Bootstrap for styling. Foundation is another good choice.
JQuery is used as the basis for Javascript event monitoring and AJAX
This is not copy and paste code. It's untested; it's purpose is to point you in the right direction.
The code is commented to help you understand what it's doing.
Since this is how SO is showing the code, we start off with the javascript and the HTML:
// this delays execution until after the page has loaded
$( document ).ready(function() {
// this monitors the button, id=submit-form-1, for a click event
// and then runs the function, submitForm1()
$('#submit-form-1').on('click', function() {
submitForm('#form1');
});
// could be repeated for another form...
$('#submit-form-2').on('click', function() {
submitForm('#form2');
});
});
// this function does an AJAX call to "insert.php".
// it expects a reply in JSON.
function submitForm(whichForm) {
var datastring = $(whichForm).serialize();
// see what you're sending:
alert('You would be sending: ' + datastring);
$.ajax({
type: "POST",
url: "insert.php",
data: datastring,
dataType: "json",
success: function(data) {
if(data.status=='success') {
alert('successfully uploaded');
} else {
alert('failed to insert');
}
},
error: function() {
alert("This example can't actually connect to the PHP script, so this error appears.");
}
});
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="produto_1">
<!--
note that the form is identified with id="form1".
"id" has to be unique. Nothing else can have id="form1".
There are no action nor method attributes,
since AJAX is submitting the form contents.
-->
<form class="form-horizontal" id="form1">
<!--
field named "action" will be used in PHP script
-->
<input type="hidden" name="action" value="insert_form_1" />
<!-- use CSS for styling, not <center>, <strong>, etc. -->
<h1 class="text-center">Produtos de Higiene</h1>
<div class="form-group">
<label for="DescricaoProd" class="col-sm-2 control-label">Nome do Produto</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoProd" name="DescricaoProd" required />
</div>
</div>
<div class="form-group">
<label for="DescricaoUnid" class="col-sm-2 control-label">Unidade</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoUnid" name="DescricaoUnid" required />
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<!--
button type is button, not submit.
Otherwise the form will try to submit.
We want the javascript to submit, not the form.
-->
<button type="button" id="submit-form-1" class="btn btn-success">Registo</button>
</div>
</div>
</form>
</section>
<!-- set up another form in the same way... -->
<form id="form2">
<input type="hidden" name="action" value="insert_form_2" />
...
<button type="button" id="submit-form-2">submit form 2</button>
</form>
The above markup and javascript should make an AJAX POST request to insert.php, and listen for a reply.
insert.php
<?php
/**
* note: It is a good practice to NEVER have anything before the <?php tag.
*
* Always try to separate logic from presentation. This is why you should
* start with PHP on the top, and never do any output until you are done
* with processing. Better yet, have separate files for logic and presentation
*
*/
// if $_POST doesn't have ['action'] key, stop the script. Every request will have
// an action.
if(!array_key_exists('action', $_POST)) {
die("Sorry, I don't know what I'm supposed to do.");
}
// database initialization could (should) go on another page so it can be reused!
// set up PDO connection
// this section credit to https://phpdelusions.net/pdo
// use your credentials here...
$host = '127.0.0.1';
$db = 'your_db_name';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
// helpful initializations, such as default fetch is associative array
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// instantiate database
$pdo = new PDO($dsn, $user, $pass, $opt);
// end database initialization
// whenever you have to do something over again, break it out into a function
// this function prevents warnings if the variable is not present in $_POST
function get_post($var_name) {
$out = '';
if(array_key_exists($var_name,$_POST)) {
$out = $_POST[$var_name];
}
return $out;
}
// assign variables
$action = get_post('action');
$name = get_post('DescricaoProd');
$unid = get_post('DescricaoUnid');
// All output of this script is JSON, so set the header to make it so.
// There can be NO output before this!
// Not even a blank line before the <?php start tag.
header('Content-Type: application/json');
// take action based on value of "action".
if($action=='insert_form_1') {
$error = false;
$output = array('message' => 'success');
// Use placeholders, never (NEVER NEVER NEVER) php variables!
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
// note, I just repeated myself, so this probably should be refactored...
// send a message back to the calling AJAX:
if($error) {
$output = array('status' => 'failed');
} else {
$output = array('status' => 'success');
}
print json_encode($output);
die; // nothing more to do
}
// you could have additional actions to perform in the same script.
// or, you could use different files...
if($action=='insert_form_2') {
// do insert for form 2
}
// etc.

Submit JQuery form multiple times without reloading page

I am trying to get my jquery form to allow for multiple submissions, but it will not load after a selection.
I have a grid (let's say 2x2). I click on a cell and fill in my name from a jquery form. I click submit and my name will appear in the cell via php. However, when I go to click on another cell the pop-up window does not appear.
I have added a simplified version of my code to jsfiddle (https://jsfiddle.net/7j7wxrpu/).
You can see from there my form is a pop-up window after you click on a cell:
<table border=1>
<tr><td colspan="11"><center><h2>Away Team</h2></center></td></tr>
<tr><th class='header-cols'></th><th class='header-cols'><h1>0</h1></th><th class='header-cols'><h1>1</h1></th></tr><tr><th class='header-rows'><h1>0</h1></th><td class='grid-cells'>
<a href='#myPopup' data-rel='popup'>
<div id='cell' onclick='setCoords(0,0);'>
<div class='grid-num'>1</div>
<div class='grid-name'>justin9</div>
</div>
</a>
</td><td class='grid-cells'>
<a href='#myPopup' data-rel='popup'>
<div id='cell' onclick='setCoords(1,0);'>
<div class='grid-num'>2</div>
<div class='grid-name'>justin10</div>
</div>
</a>
</td></tr><tr><th class='header-rows'><h1>1</h1></th><td class='grid-cells'>
<a href='#myPopup' data-rel='popup'>
<div id='cell' onclick='setCoords(0,1);'>
<div class='grid-num'>3</div>
<div class='grid-name'></div>
</div>
</a>
</td><td class='grid-cells'>
<a href='#myPopup' data-rel='popup'>
<div id='cell' onclick='setCoords(1,1);'>
<div class='grid-num'>4</div>
<div class='grid-name'></div>
</div>
</a>
</td></tr></table>
<div data-role="popup" id="myPopup" class="ui-content" style="min-width:250px;">
<form method="post" action="">
<div>
<h3>Pick This Square:</h3>
<label for="name" class="ui-hidden-accessible">Name:</label>
<input type="text" name="name" id="name" placeholder="Name">
<label for="email" class="ui-hidden-accessible">Email:</label>
<input type="text" name="email" id="email" placeholder="Email">
<input type="submit" data-inline="true" value="Submit">
<!--<input type='hidden' name='row' value=''>
<input type='hidden' name='col' value=''>-->
<div id='row-div'></div>
<div id='col-div'></div>
</div>
</form>
</div>
And here is the php it calls from the file:
<?php
include_once 'connectmysql.php';
if(!isset($_POST['name']) || !isset($_POST['email'])){
//fail because one is blank
echo "Failed the POSt data: Name: " . $_POST['name'] . " | Email: " . $_POST['email'];
}
else{
$name = $_POST['name'];
$email = $_POST['email'];
$row = $_POST['row'];
$col = $_POST['col'];
$tstamp = date("Y-m-d_H:i:s");
//Write to the sql db
$conn = ConnectMySQL();
$sql = "INSERT INTO picks (name,email,paid,row,col,tstamp) VALUES('$name','$email',0,$row,$col,'$tstamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
Besides the lack of security in my php is there anything I am missing? How come the pop-up box will only pop-up once until I refresh the page. I also notice when I refresh the page it tries to "Resend" the post data to the server. It looks like I have to clean the post data after a submit, is that a thing?
To do that without reloading the page you should use AJAX call to a PHP script that will insert the new data in the database and then query the database again and send the new values to your JavaScript and then with JavaScript to change the values of the cells.
Also, change names of the IDs - should have unique names: cell1, cell2.

redirect with php buttons in existing item-post.php

<div class="row">
<label for="AdsType"><?php _e('Ads Type', 'modern'); ?></label>
<select id="AdsType" name="AdsType" >
<option>Standard</option>
<option>Premium</option>
</select>
</div>
once user selects Standard button I want it to be redirected to www.site.com/complete.php
once user selects Premium button I want it to be redirected to www.site.com/pay.php
What is the extra coding I add in my existing php file before:
<button type="submit"><?php _e('Publish', 'modern'); ?></button>
You can change action url which is in the form using javascript
// call to change_action() function onChange event
<select id="AdsType" name="AdsType" onChange="change_action();" >
<option value="Standard">Standard</option>
<option value="Premium">Premium</option>
</select>
// change action url
<script language="javascript">
function change_action()
{
if(document.getElementById("AdsType").value=="Standard")
{
form_name.action="www.site.com/complete.php";
}
else
{
form_name.action="www.site.com/pay.php";
}
}
</script>

submit form to page and depending on input show different div

I Have a form which when submitted needs to go to the page and then show one of 4 hidden divs depending on the page.
Here is the form
<form>
<input id="place" name="place" type="text">
<input name="datepicker" type="text" id="datepicker">
<input type="submit" name="submit" id="submit" />
</form>
Here is the page
<div id="brighton">
<p>Brighton</p>
</div>
<div id="devon">
<p>Devon</p>
</div>
<div id="search">
<p>search</p>
</div>
<div id="variety">
<p>variety</p>
</div>
So if Brighton is typed into the place input i need the form to submit the page and show the Brighton div and if Devon is typed in to show the Devon div etc and if the 2/12/2012 is typed into the date picker input and Brighton into the place input it goes to the page and shows the variety div.
i also need it so if the 1/12/2012 is typed in to the date picker input the page redirects to the page show.html.
any help would be greatly appreciated
thanks.
This is easy if you know PHP at all. It looks like you need a good, easy start. Then you will be able to achieve this in seconds.
Refer to W3SCHOOLS PHP Tutorial.
To achieve what you have mentioned, first make the following changes in your form:
<form action="submit.php" method="post">
<input id="place" name="place" type="text">
<input name="datepicker" type="text" id="datepicker">
<input type="submit" name="submit" id="submit" />
</form>
Create a new file called submit.php and add the following code:
<?php
$place = $_POST['place'];
$date = $_POST['datepicker'];
if ($date == '1/12/2012') {
header('Location: show.html');
exit;
}
?>
<?php if ($place == 'Brighton''): ?>
<div id="brighton">
<p>Brighton</p>
</div>
<?php elseif ($place == 'Devon'): ?>
<div id="devon">
<p>Devon</p>
</div>
<?php elseif ($place == 'search'): ?>
<div id="search">
<p>search</p>
</div>
<?php elseif ($place == 'Variety'): ?>
<div id="variety">
<p>variety</p>
</div>
<?php endif; ?>
Now the above example is not the complete solution, but it gives you an idea as to how you can use if-then-else construct in PHP to compare values and do as desired.
Post your form to a php page and then check the posted form parameters to determine which div to show.
<?php
if ($_POST["place"] == "Brighton") {
?>
<div id="brighton">
<p>Brighton</p>
</div>
<?php
} else if ($_POST["place"] == "Devon") {
?>
<div id="devon">
<p>Devon</p>
</div>
<?php
}
?>
Do that for each div and parameter combination. Make sure you set the "method" attribute on your form to "post":
<form action="somepage.php" method="post">...</form>
In the resulting HTML you will only see the one that matches the form parameter.

Categories