php how to keep other field undisturbed while populating a combo - php

Dear users with your help and guidance I have achieved so far. Thanks to the community here. As some users felt that it was a duplicate question - sorry I changed the expected result. With members guidance i think i can achieve this.
I have a form with a textarea, a combo, a text box and other elements. First 1) I enter address in the textarea
2)I select a pincode - which is populated from a table
3)when pincode is selected the next text field is populated by the same table used in point (2) above.
For this the page is refreshed with pincode and it display the place in the next text box.
Every think ok. But what i typed in the textarea and what i selected in the combo is refreshed to blank. I need to replace what i typed and selected.
The script used for collecting the pincode
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.pin_code.options[form.pin_code.options.selectedIndex].value;
self.location='addschool.php?pin_code=' + val ;
}
</script>
The php code below:
<form data-toggle="validator" role="form">
<div class="form-group textareawidth has-feedback">
<label for="address">Enter school address</label>
<textarea class="form-control" pattern = "^[_A-z0-9]{1,}$" maxlength="150" rows ="3" name = "saddress" id="address" placeholder="Enter address with out pincode" required></textarea>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<span class="help-block with-errors"></span>
</div>
<div class="form-group textareawidth">
<label for="pin">Pincode - School:</label>
<?php
echo "<select class='form-control' id='pin' onchange=\"reload(this.form)\" name ='pin_code' name=pin_code value='' >";
echo "<option selected='selected'>Select Pincode </option>";
while($nt=mysqli_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[pin]>$nt[pin]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
</div>
<?php
$vplace="";
if(isset($_GET['pin_code']))
{
$temp=$_GET['pin_code'];
$quer="SELECT place FROM pincode where pin = $temp ";
$ex1=mysqli_query($dbcon,$quer) or die(mysql_error());
$count1=mysqli_num_rows($ex1);
if($count)
{
$row = mysqli_fetch_assoc($ex1);
$vplace = $row["place"];
}
else
{
echo '<script>';
echo 'alert("no such place found");';
echo '</script>';
}
}
?>
<div class="form-group textareawidth">
<label for="place">Place</label>
<?php
//echo "<input type ='text' class='form-control' name = 'splace' id='place' value =$vplace]>;";
echo "<p class='form-control-static'>$vplace</p>";
?>
</div>
How can I achieve this ? Thanks

According to your last comment I update the answer.
Here is an example of what you want:
in your form page (here is form.php) put the following code.
form.php:
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('#pin').change(function(e) {
var ajaxData = {
pinCode: $(this).val()
};
$.post('getPlace.php', ajaxData, function(response){
$('#place').val(response);
});
});
});
</script>
</head>
<body>
<form id="myform" name="frmForm" method="post" action="doAction.php">
<label for="address">Enter school address:</label><br>
<textarea id="address" name="txtAddress"></textarea><br>
<label for="pin">Pincode - School:</label><br>
<select id="pin" name="cmbPin">
<?php
$db = mysqli_connect('localhost','root','','testdb') or die(mysqli_connect_error());
$query = 'SELECT pin FROM pincode';
$result = mysqli_query($db,$query);
while($row = mysqli_fetch_array($result)){
echo "<option value=\"$row[pin]\">$row[pin]</option>" . PHP_EOL;;
}
?>
</select><br>
<label for="place">Place:</label><br>
<input id="place" name="txtPlace" type="text"><br>
<input id="submit" name="btnSubmit" type="submit" value="GO!">
</form>
</body>
</html>
And create an new .php file in the same directory called getPlace.php and put the php code that fetches place from your database.
getPlace.php:
<?php
if(isset($_POST['pinCode'])){
$pinCode = $_POST['pinCode'];
$db = mysqli_connect('localhost','root','','testdb') or die(mysqli_connect_error());
$query = "SELECT * FROM pincode WHERE pin = '$pinCode'";
$sql = mysqli_query($db, $query);
$result = mysqli_fetch_array($sql);
$place = $result['place'];
echo $place;
}
?>
for more information about jQuery and Ajax functions and parameters read the Documentation.

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.

Undefined index when loading page

When the page loads i get the undefined index error message enumerated 7 times, I assume it's 1 message per variable.
When I click submit all the form data still get submitted to the DB.
Once I submit the form the Undefined Index error goes away! on page reload.
Weird
<!DOCTYPE html>
<?php
$con=mysqli_connect("localhost","root","","project1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// check variables set
if (isset($_POST['submit']))
{
$site_code = $_POST['site_code'];
$site_name = $_POST['site_name'];
$site_address = $_POST['site_address'];
$site_city = $_POST['site_city'];
$site_postalcode = $_POST['site_postalcode'];
$province = $_POST['province'];
$country = $_POST['country'];
}
// Query from Countries table
$query_countries = "select * from countries";
$country_results = mysqli_query($con,$query_countries);
$number_of_returns_country = mysqli_num_rows($country_results);
// Query from Provinces Table
$query_provinces = "select * from provinces";
$provinces_results = mysqli_query($con,$query_provinces);
$number_of_returns_province = mysqli_num_rows($provinces_results);
//insert form values into sites table
$sql_site="INSERT INTO sites (site_code, site_name, site_address, site_city, site_postalcode, id_province, id_country)
VALUES
('$_POST[site_code]','$_POST[site_name]','$_POST[site_address]','$_POST[site_city]','$_POST[site_postalcode]',$_POST[province],$_POST[country])";
mysqli_query($con,$sql_site);
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="site.css">
</head>
<body>
<h1>Insert Site into DB</h1>
<h2 class="button"><a href=/index.html>Home</a></h2>
<h2 class="button"><a href=/insert.php>add site</a></h2>
<h2 class="button"><a href=/delete.html>delete site</a></h2>
<h2 class="button"><a href=/search.html>search site</a></h2>
<form class="insert" action="insert.php" method="post">
<h3>Site Info</h3>
Site code: <input type="text" name="site_code"><br>
Site name: <input type="text" name="site_name"><br>
Address: <input type="text" name="site_address"><br>
City: <input type="text" name="site_city"><br>
Postal code: <input type="text" name="site_postalcode"><br>
Province: <select name="province">
<?php while($row = mysqli_fetch_assoc($provinces_results)){ ?>
<option value="<?php echo $row['id'];?>"><?php echo $row['province'];?></option>
<?php } ?>
</select><br>
Country: <select name="country">
<?php while($row = mysqli_fetch_assoc($country_results)){ ?>
<option value="<?php echo $row['id'];?>"><?php echo $row['country'];?></option>
<?php } ?>
</select><br>
<h3>Site Contact Info</h3>
Site contact name: <input type="text" name="site_contact_name"><br>
Phone number 1: <input type="number" name="site_contact_number1"><br>
Phone number 2: <input type="number" name="site_contact_number2"><br>
Email address: <input type="email" name="site_contact_email"><br>
<input type="submit">
</form>
</body>
</html>
This happens because, when you load your page for the first time, data of the form isn't set. When you compile and send it, the error doesn't show up simply because now data is set.
You are getting the error, because there is no data in your $_POST variable. To fix it, you will have to add a name to your submit button:
<input type="submit" name="form_posted">
and enclose your PHP code into this if:
if(isset($_POST['form_posted'])) {
}
Alternatively, you can add this on top of your PHP, to exclude warnings:
error_reporting(E_ALL ^ E_WARNING);

How do I update input values with db values after a select OnChange with idealforms?

I'm using idealforms from elclanrs and I have a select which is filled from a database. OnChange I want to update the value of the input fields with information from the database. In this case, firstname, lastname. I tried it with AJAX but that didn't work out because when the form values where getting renewed, the whole idealforms makeup of the form vanishes.
I looked through stackoverflow and saw it was a fairly common problem but I still can't seem to work it out. I used this and it didn't work, maybe because I placed it in the wrong order?
This is my code:
<form id="my-form" action="EditAccountHandler.php" method="post">
<?php
include 'conn/dbConnect.php';
echo '<div><label>Gebruikers</label><select id="gebruiker" selected="$sUsername" name="selectedUser" onchange="updateInput(this.value)">';
$sqEditUser = mysql_query("SELECT * FROM account a, persoon p WHERE a.idSuper = p.idUser", $con);
while($row = mysql_fetch_array($sqEditUser))
{
$iIdUser = $row['idUser'];
$sFirstname = $row['Voornaam'];
$sLastname = $row['Achternaam'];
$sUsername = "{$sLastname}, {$sFirstname}";
echo "<option value='$iIdUser'>$sUsername</option>";
}
echo "</select></div>";
?>
<script>
function updateInput(<?= json_encode($sFirstname); ?>)
{
document.getElementById("naam").value = <?php echo json_encode($sFirstname); ?>;
}
</script>
<div><label>Voornaam</label><input id="naam" name="naam" type="text"/></div>
<div><label>Achternaam</label><input id="anaam" name="anaam" type="text"/></div>
<div>
<button id="reset" type="button">Reset</button>
<button type="submit">Wijzigen</button>
</div>
</form>
This is what I'm trying to achieve:
Example picture
I'm not sure about what I am doing wrong. Can yo guys help me?
Edit
Removed code that was double in comparison with the first codesnippet.
Added echo
Removed action="EditAccountHandler.php"
Added idealforms validation code
Replaced with final code
<div id="main">
<h3>Wijzig Account</h3><br />
<form id="myselect" action="" method="post">
<div>
<label>Gebruikers</label><select id="gebruiker" selected="$sUsername" name="selectedUser" onchange="this.form.submit()">
<?php
include 'conn/dbConnect.php';
$sqUser = mysql_query("SELECT * FROM account a, persoon p WHERE a.idSuper = p.idUser", $con);
while($row = mysql_fetch_array($sqUser))
{
$iIdUser = $row['idUser'];
$sFirstname = $row['Voornaam'];
$sLastname = $row['Achternaam'];
$sUsername = "{$sLastname}, {$sFirstname}";
echo "<option value='$iIdUser'>$sUsername</option>";
}
?>
</select>
</div>
</form>
<script>
var options = { onFail: function(){alert('Selecteer een persoon')}};
var $myform1 = $('#myselect').idealforms(options).data('idealforms');
$myform1.focusFirst();
</script>
<?php
if(!empty($_POST['selectedUser']))
{
$sqGetUser = mysql_query("SELECT * FROM persoon WHERE idUser = '$_POST[selectedUser]'", $con);
while($row = mysql_fetch_array($sqGetUser))
{
$sFname = $row['Voornaam'];
$sLname = $row['Achternaam'];
}
?>
<form id="my-form" action="EditAccountHandler.php" method="post">
<div><label>Voornaam</label><input id="naam" name="naam" value="<?php echo htmlspecialchars($sFname); ?>" type="text"/></div>
<div><label>Achternaam</label><input id="anaam" name="anaam" value="<?php echo htmlspecialchars($sLname); ?>" type="text"/></div>
<div>
<label>Rechten</label>
<label><input type="radio" name="rechten" value="Administrator"/>Administrator</label>
<label><input type="radio" name="rechten" value="Contentmanager"/>Contentmanager</label>
<label><input type="radio" name="rechten" value="Administratie"/>Administratie</label>
<label><input type="radio" name="rechten" value="Medewerker"/>Medewerker</label>
<label><input type="radio" name="rechten" value="Klant" checked/>Klant</label>
<label><input type="radio" name="rechten" value="Gast"/>Gast</label>
<label><input type="radio" name="rechten" value="MedeKlant"/>MedeKlant</label>
</div>
<div>
<button id="reset" type="button">Reset</button>
<button type="submit">Wijzigen</button>
</div>
</form>
</div>
</div>
<script>
var options =
{
onFail: function()
{
alert( 'Vul alle velden correct in.' )
},
inputs:
{
'anaam':
{
filters: 'required name',
},
'naam':
{
filters: 'required name',
},
}
};
var $myform = $('#my-form').idealforms(options).data('idealforms');
$('#reset').click(function(){ $myform.reset().fresh().focusFirst() });
$myform.focusFirst();
</script>
<?php
}
?>
I think you are messing client code with server code.
Once the onChange event is fired, you have to reload the page for example onChange="this.form.submit()" and you verify if(!empty($_POST["selectedUser"])) then you fill the fields of the form with the data you can obtain with a new SQL query, where id = $_POST["selectedUser"].
In this case you don't need the updateuser function.
If you use AJAX, you would need the updateuser function, but you have got to get rid of the json_encode methods which execute on server, and with ajax everything is in the client part. It would be simply: "function updateuser(id)".
You can use jquery to do the ajax call to get the info, and then you fill the form fields.
EDIT:
Examining the new code you provide. I see one error, you are using htmlspecialchars function but you are not echoing it, ;-). You should use "echo ...".
For the form, you should use "this.form.submit()" if you are inside the form labels.
If you use jquery it would be something like this:
<script type="text/javascript">
$("#selectedUser").change(function()
{
if(this.form.elements['selectedUser'].value!="")
{
this.form.submit();
}
});
</script>

how to submit div in a form

I am using ckeditor in order to edit the text seen in the screen. The information is taken from database and written to the screen in a div element and it is possible to edit the information by double clicking. However, after edited i couldn't get the edited information. Here is my code, i tried to add a form which includes the div element, but it did not work.
<form method="post">
<p>
Double-click any of the following <code><div></code> elements to transform them into
editor instances.</p>
<?php
$makeleSql = 'SELECT * FROM makale';
$makaleRs = $con->func_query($makeleSql);
while ($makaleRow = mysql_fetch_array($makaleRs)) {
?>
<div class = "editable" id = <?php echo "content".$makaleRow['id'];?> style="display:none">
<?php
$contentSql = 'SELECT * FROM content WHERE makale_id ='.$makaleRow['id'];
$contentRs = $con->func_query($contentSql);
while ($contentRow = mysql_fetch_array($contentRs)) {
echo $contentRow['icerik'].$makaleRow['id'];
}
?>
</div>
<?php }
?>
<button type="submit" value="Submit" onclick="getDiv();"/>
</form>
What should i do in order to take the information in the div element? Moreover, i am using this example.
http://nightly.ckeditor.com/7484/_samples/divreplace.html
Thanks.
For save form's data you need store information in input/select/textarea. Div and other not form's element not will be stored.
You have to store your data in hidden fields:
<form method="post">
<p>
Double-click any of the following <code><div></code> elements to transform them into
editor instances.</p>
<?php
$makeleSql = 'SELECT * FROM makale';
$makaleRs = $con->func_query($makeleSql);
while ($makaleRow = mysql_fetch_array($makaleRs)) {
?>
<div class="editable" id="<?php echo "content".$makaleRow['id'];?>">
<?php
$contentSql = 'SELECT * FROM content WHERE makale_id ='.$makaleRow['id'];
$contentRs = $con->func_query($contentSql);
while ($contentRow = mysql_fetch_array($contentRs)) {
echo $contentRow['icerik'].$makaleRow['id'];
// store original text
echo '<input type="hidden" name="'.$makaleRow['id'].'" value="'.htmlspecialchars($contentRow['icerik'].$makaleRow['id']).'">;
}
?>
</div>
<?php }
?>
<button type="submit" value="Submit" onclick="getDiv(this);"/>
</form>
<script>
var getDiv = function(btn) {
for(var el in btn.form.elements) {
var d = document.getElementById(btn.form.elements[el].name);
btn.form.elements[el].value = d.innerHTML;
}
return true;
}
</script>
Generically adds <input type="hidden"> to any <div> with the attribute addToForm, copies content into them (see notes below):
<form method="post" id="f">
<div id="txt" addToForm="1" contenteditable spellcheck="true" style="height:100px;width:300px;font-family:arial,sans serif;border:1px solid black;font-weight:normal;overflow-y:auto;"
</div><br />
<input type="button" value="Go" id="btnGo">
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#btnGo").click(function(){
$("div[addToForm]").each(function(){
var tId=$(this).prop("id");
$(this).after("<input type='hidden' name='"+tId+"' id='hdn"+tId+"'>");
$("#hdn"+tId).val($(this).html());
});
$("#f").submit();
});
});
</script>
Note 1) if you want to strip out the HTML formatting of the content, use <textarea> instead of <input>
Note 2) be sure validation is successfully complete first or you will end up with multiple hidden inputs with the same name

Categories