Keep the form open when sending data to the table - php

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.

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?

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

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>

Validate Data & insert data into mysql

I am making a helpdesk page where i have page to raise a ticket. I have form where i want Issue Type & Query field to be filled mandatory & validate data for extension no. i.e it should be in no. only.
I have tried code to get it via ajax & form validation but not able to execute the code & values are not getting inserted into the mysql db.
Please Help !
Ticket.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Raise Ticket</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
// Form validation.
if ($('.validate-issue').val() === '') { $('.issue-error').fadeIn(); }
if ($('.validate-query').val() === '') { $('.query-error').fadeIn(); }
// Grab form values
var formData = {
'ename' : $('input[name=ename]').val(),
'date' : $('input[name=date]').val(),
'ext' : $('input[name=ext]').val(),
'issue' : $('select[name=issue]').val(),
'query' : $('input[name=query]').val(),
'upload' : $('input[name=upload]').val()
};
if($('.validate-issue').val().trim()) &&($('.validate-query').val().trim()){
// Ajax form submit.
$.ajax({
type: "POST",
url: "insertticket.php",
data: formData,
success: function()
{
alert('Ticket has been raised');
}
});
} else { alert('Please enter the mandatory fields'); } });
});
</script>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><h1 align="center">Helpdesk-Support</h1></div>
<hr>
<div class="panel-body" align="center">
<h2>Raise Ticket!</h2>
<form class="form-horizontal" role="form" enctype="multipart/form-data" method="post">
<div class="form-group">
<label class="control-label col-sm-2" for="text">Name:</label>
<div class="col-sm-10">
<input type="text" disabled class="form-control" id="text" name="ename" value="<?php echo ucwords($_SESSION['usr_name']); ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="date">Date:</label>
<div class="col-sm-10">
<input type="text" class="form-control" disabled id="date" name="date" value="<?php date_default_timezone_set("Asia/Calcutta"); echo date('Y-m-d H:i:s')?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="ext">Extension No.:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="ext" name="ext" placeholder="Enter Extension No.">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="issue">Issue Type:</label>
<div class="col-sm-10">
<select class="form-control" id="validate-issue" name="issue"><span class="issue-error">Enter Issue Type</span>
<option>Select an option</option>
<option>Hardware Issue</option>
<option>Network Issue</option>
<option>Software Issue</option>
<option>ERP</option>
<option>CRM</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="query">Query:</label>
<div class="col-sm-10">
<textarea rows="5" class="form-control" id="validate-query" name="query" placeholder=" Enter Query here"></textarea><span class="query-error">Enter Detailed Query</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Upload File:</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="filetoupload" name="upload" >
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<div class="panel-footer" align="center">&copy Copyright <?php echo date("Y");?></div>
</div>
</div>
</body>
</html>
insertticket.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="helpdesk"; // Database name
// Connect to server and select database.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$emp_name = mysqli_real_escape_string($conn, $_POST['ename']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$issue_type = mysqli_real_escape_string($conn, $_POST['issue']);
$query = mysqli_real_escape_string($conn, $_POST['query']);
$ext_no. = mysqli_real_escape_string($conn, $_POST['ext']);
$attachment = mysqli_real_escape_string($conn, $_POST['upload']);
$sqli="select * from user where name='$emp_name'";
$result=mysqli_query($conn,$sqli);
while($row=mysqli_fetch_array($result))
{
$emp_code=$row['emp_code'];
$dept=$row['dept'];
$location=$row['location'];
$emailid=$row['emailid'];
$contact_no.=$row['contact_no.'];
}
$sql="INSERT INTO ticket (ticket_no.,emp_code,emp_name,dept,location,emailid,contact_no.,date,issue_type,query,ext_no.,attachment)
VALUES('','$emp_code','$emp_name','$dept','$location','$emailid','$contact_no.','$date','$issue_type','$query','$ext_no.','$attachment')";
if (mysqli_query($conn,$sql))
{
echo "Record added";
}
else
{
die('Error: ' . mysqli_error());
}
?>
Your triggering your script on its first load only. You can try .submit() of jQuery.
I'm not also certain if you can upload files just by getting its content by name/class/id.
Isn't .trim() just for removing extra spaces, and not for checking content?
What is up with those dots(.) in your column names anyway?
You should use $_FILES["upload"]["name"] instead of $_POST["upload"] for getting the file name attached by the user
Where is your code for uploading the file?
You can try required attribute of HTML for the meantime:
<input required="true" type="text" disabled class="form-control" id="text" name="ename" value="<?php echo ucwords($_SESSION['usr_name']); ?>">
And why don't we try .submit() in your case:
First, we have to give a unique data attribute for your <form> by adding an id attribute.
<form id="form-submission" class="form-horizontal" role="form" enctype="multipart/form-data" method="post">
Then for your script:
$(document).ready(function(){
$("form#form-submission").submit(function(){ /* WHEN THE FORM IS SUBMITTED */
var formData = new FormData($(this)[0]); /* ALL THE DATA IS IN HERE INCLUDING THE FILE ATTACHED */
$.ajax({ /* CALL AJAX */
url: "insertticket.php", /* THE FILE WHERE THE DATA WILL GO */
type: "POST", /* TYPE OF METHOD TO BE USED TO PROCESS THE DATA */
data: formData, /* THE DATA TO BE PROCESSED */
contentType: false, /* TYPE OF DATA TO BE PASSED; FOR FILE PURPOSES THAT IS WHY IT IS SET TO FALSE */
processData: false, /* PREVENT AUTOMATIC PROCESSING */
success: function(result){ /* IF DATA IS PROCESSED SUCCESSFULLY */
alert(result); /* ALERT THE RETURNED DATA FROM inserticket.php */
}
});
return false;
});
});
You're also already using mysqli_, so its easier to convert your code to prepared statement instead.
This is your insertticket.php:
<?php
$conn = new mysqli("localhost", "root", "", "helpdesk");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT emp_code, dept, location, emailid, contact_no FROM user WHERE name = ?")){ /* PREPARE YOUR QUERY */
$stmt->bind_param("s", $_POST["ename"]); /* BIND THIS DATA TO YOUR QUERY, REPLACING ? WITH $_POST["ename"]; s STANDS FOR STRING TYPE */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($emp_code, $dept, $location, $emailid, $contact_no); /* BIND THE RESULTS TO THESE VARIABLES CORRESPONDINGLY */
$stmt->fetch(); /* FETCH THE RESULT */
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
if($stmt = $con->prepare("INSERT INTO ticket (emp_code, emp_name, dept, location, emailid, contact_no, date, issue_type, query, ext_no, attachment) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")){
$stmt->bind_param("sssssssssss", $emp_code, $_POST["ename"], $dept, $location, $emailid, $contact_no, $_POST["date"], $_POST["issue"], $_POST["query"], $_POST["ext"], $_FILES["upload"]["name"]);
$stmt->execute();
$stmt->close();
echo 'Record added';
}
move_upload_file($_FILES["upload"]["tmp_name"], "/system/uploads/".$_FILES["upload"]["name"]); /* UPLOAD THE FILE TO /system/uploads/ FOLDER; JUST REPLACE YOUR DESIRED DIRECTORY */
?>
Always take a look at your browser's console log for errors
You should also consider renaming the uploaded file by the user through your code so that it will be unique inside your folder and database. To prevent duplicate file name that would lead to overwriting of files

php how to keep other field undisturbed while populating a combo

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.

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>

Categories