How to retain dropdown value after the page is reloaded? - javascript

How to retain my dropdown value after page reload? The form reloads after I submit and validates an error. Now I just want to retain the dropdown value after the form gets an error.
if(isset($_POST['mod_simpleemailform_submit_1']))
{
$day = $_POST['mod_simpleemailform_field1_1'];
$month = $_POST['mod_simpleemailform_field2_1'];
$year = $_POST['mod_simpleemailform_field3_1'];
$time = $_POST['mod_simpleemailform_field4_1'];
$guest = $_POST['mod_simpleemailform_field5_1'];
$name = $_POST['mod_simpleemailform_field6_1'];
$email = $_POST['mod_simpleemailform_field7_1'];
$menu = $_POST['mod_simpleemailform_field8_1'];
$inquiry = $_POST['mod_simpleemailform_field9_1'];
if(!$day)
{
$dayError = "Please enter a value for required field: Day";
}
if(!$month)
{
$monthError = "Please enter a value for required field: Month";
}
if(!$year)
{
$yearError = "Please enter a value for required field: Year";
}
if(!$time)
{
$timeError = "Please enter a value for required field: Time";
}
if(!$guest)
{
$guestError = "Please enter a value for required field: Guest";
}
if(!$name)
{
$nameError = "Please enter a value for required field: Name";
}
if($name!="")
{
if(!letter($name)) { $nameError .= "Please enter letters only for Name";}
}
if(!$email)
{
$emailError = "Please enter a value for required field: Email";
}
if($email!="")
{
if(!isemail($email)) { $emailError .= "Please enter a invalid Email";}
}
if(!$menu)
{
$menuError = "Please enter a value for required field: Menu";
}
if(!$inquiry)
{
$inquiryError = "Please enter a value for required field: Message";
}
if($dayError=="" && $monthError=="" && $yearError=="" && $timeError=="" && $guestError=="" && $nameError=="" && $emailError=="" && $menuError=="" && $inquiryError=="")
{
$to = "joomla.hbtest#gmail.com";
$subj = "Beledutung Inquiry Form";
$msg = "\n\n";
$msg .= "Date: ".$day." / ".$month." / ".$year."\n";
$msg .= "Time: ".$time."\n";
$msg .= "Guest: ".$guest."\n";
$msg .= "Name: ".$name."\n";
$msg .= "Email: ".$email."\n";
$msg .= "Menu: ".$menu."\n";
$msg .= "----------------------------------------------\n\n";
$msg .= "Message: ".$inquiry."\n";
$head = "From: \"$name\" <$name>\n";
$head .= "Reply-To: \"$email\" <$email>\n";
$head .= "Return-Path: \"$email\" <$email>\n";
if(mail($to,$subj,$msg,$head))
{
?>
<script type="text/javascript">
alert("Your message has been sent we will come back to you shorty.");
window.location = "booking.php";
</script>
<?php
}
}
}
?>
<form method="post" action="booking.php" name="_SimpleEmailForm_1" id="_SimpleEmailForm_1" enctype="multipart/form-data" class="tt-form booking-form padding-top margin-top">
<table class="mod_sef_table">
<tbody></tbody>
<div id="message">
<div class="error"><?php echo $dayError;?></div>
<div class="error"><?php echo $monthError;?></div>
<div class="error"><?php echo $yearError;?></div>
<div class="error"><?php echo $timeError;?></div>
<div class="error"><?php echo $guestError;?></div>
<div class="error"><?php echo $nameError;?></div>
<div class="error"><?php echo $emailError;?></div>
<div class="error"><?php echo $menuError;?></div>
<div class="error"><?php echo $inquiryError;?></div>
</div>
<div class="row1 row form-row">
<tr class="mod_sef_tr col-md-2 column no-padding">
<th align="center" style="text-align:center;" class="mod_sef_th">Day</th>
<td class="mod_sef_space" width="5"> </td>
<td class="mod_sef_td input-cover contact-line" id="store">
<select name="mod_simpleemailform_field1_1" id="mod_simpleemailform_field1_1" class="mod_sef_input_select select" value="<?php echo $day; ?>">
<option value="">Day</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
</td>
</tr>
</div>
</table>
</html>

You can use localStorage to store selected value:
$('#mod_simpleemailform_field1_1').on('change', function() {
// Save value in localstorage
localStorage.setItem("mod_simpleemailform_field1_1", $(this).val());
});
On page refresh, get the value from localStorage and set to the select:
$(document).ready(function() {
if ($('#mod_simpleemailform_field1_1').length) {
$('#mod_simpleemailform_field1_1').val(localStorage.getItem("mod_simpleemailform_field1_1"));
}
});
localStorage is not supported in all browsers. You can use shims for that or fallback to cookie.

It is possible through PHP and you are doing it wrong select elements do not have value attributes:
So first of all remove value attribute:
<select name="mod_simpleemailform_field1_1" id="mod_simpleemailform_field1_1"
class="mod_sef_input_select select" value="<?php echo $day; ?>">
And use selected attribute on option tag.
<select name="mod_simpleemailform_field1_1" id="mod_simpleemailform_field1_1"
class="mod_sef_input_select select">
<option value="">Day</option>
<?php
for($i = 1; $i <= 10; $i++) {
if($day == $i) {
echo '<option selected="selected">' . $i . '</option>';
} else {
echo '<option>' . $i . '</option>';
}
}
</select>

you can use local storage
// set value of dropdown into local storage
localStorage.setItem("StorageName", "DropDownValue");
// retrieve value from local storage
var ddlValue = localStorage.getItem("StorageName");

Related

echo php form validation with ajax

Good day to everyone,
I am trying to create a CMS with php and I am having a trouble to do the next:
I want to delete, edit or add information to my page, so to do it I am using several buttoms and AJAX to load the form to a display div. I get the button delete to work perfectly, but when I try the add and edit button it doesn´t work due to that they ask to append some html text that also contains php code so there is no PHP interpreter to read it.
My approach:
<div class="displayHere col-xs-12"> </div> is empty.
I click Add button, It goes to ajax.php and append the form and form validation.
I filled the form and click add_document, the form validation (php) check the datas and upload the document if it is possible and set some outputs variables.
How can I get this functionality? Probably I am approaching badly the problem, I hope some of you can share your experience with me.
For example, for the add function, I want to get this functionality:
<div id="bodyDiv">
<!--HEADER-->
<header id="header" class=" row">
<?php
include 'includes/loadHeader.php';
echo '<nav class="col-xs-6 cms_nav">
<ul>
<li><input id="buttonAdd" type="submit" class="button buttonFuncitonality" name="AÑADIR" value="AÑADIR" /></li>
</ul>
</nav>';
?>
<div class="displayHere col-xs-12">
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$nameErr = $dateErr = $typeErr = $fileErr = "";
$name = $date = $type = $file = $matches = "";
$success = true;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
// name, date, type, path
if (empty($_POST["name"])) {
$nameErr = "El nombre es necesario";
$success = FALSE;
}
else {
$name = test_input($_POST["name"]);
}
if (!empty($_POST["date"])) {
$date = test_input($_POST["date"]);
$time_pattern = "(([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))?";
//Check the date format http://www.phpliveregex.com/ (0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s+([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])
if (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s*".$time_pattern."/",$date,$matches)){
echo "<script>console.log('yeahh format 1');</script>";
echo "<script>console.log('yeahh format 1 ". $date. " ". str_replace("-","/",$matches['0']) ." yeahh format 1');</script>";
$date = str_replace("-","/",$matches['0']);
}
elseif (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})\s*".$time_pattern."/",$date, $matches)){
}
else{
echo "<script>console.log('noooo ". $date. " " . $matches['0'] ." yeahh format 1');</script>";
$dateErr = "Formato de fecha incorrecto";
$success = FALSE;
}
//The formar mysql is expecting DATETIME '0000-00-00 00:00:00'
if(empty($dateErr)){
if( preg_match("/\s([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])/",$date)){
$date = DateTime::createFromFormat('j/m/Y H:i', $date);
$date = $date->format('d-m-Y H:i');
}
else{
$date = DateTime::createFromFormat('j/m/Y', $date);
$date = $date->format('d-m-Y');
}
echo "<script>console.log('date ".$date."');</script>";
}
}
if (empty($_POST["type"]) ) {
$typeErr = "El tipo de documento es necesario";
$success = FALSE;
}
else{
$type = test_input($_POST["type"]);
}
// Upload the file
if($success ){
if(empty($_FILES['documentPDF']['name'])){
$fileErr = "Debes añadir un documento pdf ";
}
else{
$target_dir = "shareholders_documents/".$type. "/";
$file_name = basename($_FILES["documentPDF"]["name"]);
$target_file = $target_dir . $file_name;
echo "<script>console.log('".$target_file."');</script>";
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//echo " vamos a ver que hay aqui " .$target_file;
// Check if pdf already exist
if (file_exists($target_file)) {
$fileErr = "Este documento ya existe.";
$success = false;
}
if ($_FILES["documentPDF"]["size"] > 500000) {
$fileErr = "El documento es demasiado largo";
$success = false;
}
// Allow certain file formats
if($fileType != "pdf" ) {
$fileErr = "El documento debe estar en formato pdf";
$success = false;
}
// Check if $uploadOk is set to 0 by an error
if ($success == true ) {
//echo "\nmove_uploaded_file(".$_FILES["documentPDF"]["tmp_name"].", ".$target_file.")" ;
if (!move_uploaded_file($_FILES["documentPDF"]["tmp_name"], $target_file)) {
$fileErr ="No se ha podido almacenar el documento ". basename( $_FILES["documentPDF"]["name"]);
$success = false;
}
}
}
}
}
$result="";
// Now we have to prepare the data for the sql operation
if( isset( $_POST["insert"] ) && $success ){
$name = test_input($_POST['name']);
$date = $date;
$type = test_input($_POST['type']);
$path = $file_name;
$id = $type ." ". $date . " " . $path ;
//Create $sql sentence
$sql = "INSERT INTO `shareholders_documents`(`id`, `name`, `date`, `type`, `path`) VALUES ('".$id."','".$name."',STR_TO_DATE('".$date."', '%d-%m-%Y %H:%i'),'".$type."','".$path."')";
$sqlResult = $conn->query($sql);
$message= "";
if($conn->error){
$message = $conn->error;
$success = false;
}
//Sending email
if ($success){
$result='<div class="alert alert-success margin-top-big">El documento se ha subido correctamente'.$name." ".$date." ".$type." ". $path. "\n" . $sql. '</div>';
}
else{
$result = '<div class="alert alert-danger margin-top-big">Algo ha fallado y el documento no se ha podido subir ' . $message . '</div>';
if(empty($fileErr)){ //If we cannot insert the document we must delete the file
unlink($target_file);
}
}
}
//Cleaning global array $_POST
$_POST = array();
$_FILE = array();
?>
<div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control <?php if( !empty($nameErr) ) {echo 'boxError alert-danger ' ;} ?> " value="<?php if( !$success ) {echo $name;}?>" type="text" name="name" placeholder="<?php if( !empty($nameErr) ) {echo $nameErr;}else{ echo 'nombre';}?>">
<input class="col-xs-12 form-control <?php if( !empty($dateErr) ) {echo 'boxError alert-danger ' ;} ?> " value="<?php if( !$success ) {echo $date;}?>" type="text" name="date" placeholder="<?php if( !empty($dateErr) ) {echo $dateErr;}else{ echo 'fecha (Ejemplo de formato: 31/10/2017 17:54)';}?>">
<select class="col-xs-12 form-control <?php if( !empty($typeErr) ) {echo 'boxError alert-danger ' ;} ?> " name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12" type="file" name="documentPDF" accept="application/pdf" >
<span class="error col-xs-12" style="float:left"> <?php if( !empty($fileErr) ) {echo "* ". $fileErr;} ?> </span>
<button class="btn btn-default" type="submit" name="insert">Añadir</button>
<?php if ( !empty($result) ){ echo $result; } ?>
</form>
</div>
</div>
In my website I have a add button which should upload the form validation using AJAX.
<?php
//echo "piece of shit";
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'AÑADIR': //ADD FUNCTIONALITY
add_document();
break;
default:
echo "La accion no se indentifica\n" ;
break;
}
}
function add_document() {
echo ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control <?php if( !empty($nameErr) ) {echo "boxError alert-danger " ;} ?> " value="<?php if( !$success ) {echo $name;}?>" type="text" name="name" placeholder="<?php if( !empty($nameErr) ) {echo $nameErr;}else{ echo "nombre";}?>">
<input class="col-xs-12 form-control <?php if( !empty($dateErr) ) {echo "boxError alert-danger " ;} ?> " value="<?php if( !$success ) {echo $date;}?>" type="text" name="date" placeholder="<?php if( !empty($dateErr) ) {echo $dateErr;}else{ echo "fecha (Ejemplo de formato: 31/10/2017 17:54)";}?>">
<select class="col-xs-12 form-control <?php if( !empty($typeErr) ) {echo "boxError alert-danger" ;} ?> " name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12" type="file" name="documentPDF" accept="application/pdf" >
<span class="error col-xs-12" style="float:left"> <?php if( !empty($fileErr) ) {echo "* ". $fileErr;} ?> </span>
<button class="btn btn-default" type="submit" name="insert">Añadir</button>
<?php if ( !empty($result) ){ echo $result; } ?>
</form>
</div>
</div>';
}
function load_delete_document_form($id) {
echo ' <div id="deleteForm" class="col-xs-12 shareholdersForm">
<h3>Eliminar '. $id.'</h3>
<form id="'.$id.'" method="POST">
<button class="btn btn-default buttonFunctionality" type="submit" name="Delete" value="Delete">Eliminar</button>
</form>
</div>
';
exit;
}
?>
To use that AJAX code I use this jquery function in my website:
<script>
//$(document).ready(function(){
$("body").on("click",".buttonFunctionality", function(){
if($('.displayHere').length !== 0){
$('.displayHere').children().remove()
}
var action = $(this).val();
var id = $(this).parent().attr('id');
console.log(action + " " + id);
$.post("includes/ajax.php",{ action: action, id: id}, function(data, status){
console.log("click1 " + id );
console.log("data " + data);
$('.displayHere').append(data); // This append will append the code I will need in my page
});
});
//});
</script>
As a result of my code I get the form with a buch of php code without interpretation.
I think you can check it with html attribute required for empty input
and for other like user just entered spaces in comment input using php function empty($value)
The Issue is from your add_document() function;
since it's php you don't have to use <?php ?> but instead concatenate the strings together and then echo the whole thing
Should looks like this :
function add_document() {
$div = ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control ';
if( !empty($nameErr) ) {
$div .= "boxError alert-danger ";
}
$div .= '" value="';
if( !$success ) {
$div .= $name;
}
$div .= '" type="text" name="name" placeholder="';
//more code
echo $div;
}
Hope you get the idea
Edit :
The other issue here is the fact that you are trying to do form verif on the ajax side of the form without re-submiting it;
I would suggest using default form validation by adding required to your input tags;
Your function should look like that :
function add_document() {
$nameVal = (!$success ) ? $name : "";
$dateVal = (!$success ) ? $date : "";
$resultVal = (!empty($result) ) ? $result : "";
$nameErrVal = (!empty($nameErr)) ? $nameErr : "nombre";
$dateErrVal = (!empty($dateErr)) ? "boxError alert-danger " : "";
$dateErrVal2 = (!empty($dateErr)) ? $dateErr : "fecha (Ejemplo de formato: 31/10/2017 17:54)";
$typeErrVal = (!empty($typeErr)) ? "boxError alert-danger" : "";
$fileErrVal = (!empty($fileErr)) ? "* ". $fileErr : "";
$div = ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control " value="'.$nameVal.'" type="text" name="name" placeholder="'
.$nameErrVal.'" required>
<input class="col-xs-12 form-control '.$dateErrVal.'" value="'.$dateVal.'"
type="text" name="date" placeholder="'.$dateErrVal2.'" required>
<select class="col-xs-12 form-control '.$typeErrVal.'" name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12" type="file" name="documentPDF" accept="application/pdf" required>
<span class="error col-xs-12" style="float:left"> '.$fileErrVal.' </span>
<button class="btn btn-default" type="submit" name="insert">Añadir</button>
'.$resultVal.'
</form>
</div>
</div>';
echo $div;
}
It should output something like that : https://jsfiddle.net/p6147nh0/11/
Finally I found a solution to this. It was my first approach:
<div class="displayHere col-xs-12"> </div> is empty.
I click Add button, It goes to ajax.php and append the form and form
validation. (This part is wrong or at least I did not get it to
work, I cannot append the form valitation to the front. Instead, I
have to check everything to the AJAX file which will check
everything and will return just the html already formed.)
3- I filled the form and click add_document, the form validation (php)
check the datas and upload the document if it is possible and set
some outputs variables.
As it did not work, I tried to send to my AJAX all the information needed to validate the form and get from it just the html already created.
is empty.
I click the button ADD (there are two add buttons, one to upload the form and other to send the form filled), it will go to AJAX and will return to me the
form that will be appened to the page.
hecho relevantes
informacion empresa
informacion financiera
Añadir
The form will be filled and the Añadir click. The button has associated a
javascript function.
$(document).ready(function(){
$("body").on("click",".buttonFunctionality", function(e){
e.preventDefault();
var action = $(this).val();
var id = $(this).parent().attr('id');
var formdata = new FormData($("#insertForm>form")[0]);
formdata.append("action", action);
formdata.append("id",id);
$.ajax({
url: "includes/ajax.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formdata, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log("SUCCESS");
if($('.displayHere').length !== 0){
$('.displayHere').children().remove()
}
$(".displayHere").append(data);
}
});
});
});
//});
</script>
3-At the begining I tried to create a JSON to send the information to my ajax.php, but then, I realised there is a method var formdata = new FormData($("#insertForm>form") that gave the all the information I need to deal with the form valitation ($_POST, $_File ... ). So finally this method was the last detail I needed to solve it.
This function send to ajax.php the information, and in ajax.php deals with the php code.
AJAX.php
<?php
session_start();
include 'dbh.inc.php';
$message = $sql = "";
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'AÑADIR':
add_document($_POST['action']);
break;
case 'add':
echo("<script>console.log(' ADD ');</script>");
echo("<script>console.log(' PHP tmp_name :". $_FILES['documentPDF']['tmp_name']."');</script>");
if(isset($_FILES["documentPDF"]["type"]))
{
echo("<script>console.log(' PHP tmp_name :". $_FILES['documentPDF']['tmp_name']."');</script>");
}
add_document($_POST['action']);
break;
case 'Editar':
if (isset($_POST['id'])) {
load_edit_document($_POST['id']);
break;
}
case 'Edit':
if (isset($_POST['id'])) {
edit_document($_POST['id']);
break;
}
case 'Eliminar':
if (isset($_POST['id'])) {
echo("<script>console.log('PHP id: ".$_POST['id']."');</script>");
load_delete_document_form($_POST['id']);
break;
}
case 'Delete':
if (isset($_POST['id'])) {
delete_document($_POST['id']);
break;
}
default:
echo "La accion no se indentifica\n" ;
break;
}
}
function add_document($action) {
echo "<script>console.log('INSIDE ADD_DOCUMENT');</script>";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$nameErr = $dateErr = $typeErr = $fileErr = "";
$name = $date = $type = $file = $matches = "";
$success = true;
if ($_SERVER["REQUEST_METHOD"] == "POST" && $action == 'add' ){
echo "<script>console.log('INSIDE REQUEST_METHOD');</script>";
// name, date, type, path
if (empty($_POST["name"])) {
$nameErr = "El nombre es necesario";
$success = FALSE;
}
else {
$name = test_input($_POST["name"]);
}
if (!empty($_POST["date"])) {
$date = test_input($_POST["date"]);
$time_pattern = "(([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))?";
//Check the date format http://www.phpliveregex.com/ (0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s+([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])
if (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s*".$time_pattern."/",$date,$matches)){
echo "<script>console.log('yeahh format 1');</script>";
echo "<script>console.log('yeahh format 1 ". $date. " ". str_replace("-","/",$matches['0']) ." yeahh format 1');</script>";
$date = str_replace("-","/",$matches['0']);
}
elseif (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})\s*".$time_pattern."/",$date, $matches)){
}
else{
echo "<script>console.log('noooo ". $date. " " . $matches['0'] ." yeahh format 1');</script>";
$dateErr = "Formato de fecha incorrecto";
$success = FALSE;
}
//The formar mysql is expecting DATETIME '0000-00-00 00:00:00'
if(empty($dateErr)){
if( preg_match("/\s([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])/",$date)){
$date = DateTime::createFromFormat('j/m/Y H:i', $date);
$date = $date->format('d-m-Y H:i');
}
else{
$date = DateTime::createFromFormat('j/m/Y', $date);
$date = $date->format('d-m-Y');
}
echo "<script>console.log('date ".$date."');</script>";
}
}
if (empty($_POST["type"]) ) {
$typeErr = "El tipo de documento es necesario";
$success = FALSE;
}
else{
$type = test_input($_POST["type"]);
}
// Upload the file
if($success ){
if(empty($_FILES['documentPDF']['name'])){
$fileErr = "Debes añadir un documento pdf ";
}
else{
$target_dir = "../shareholders_documents/".$type. "/";
$file_name = basename($_FILES["documentPDF"]["name"]);
$target_file = $target_dir . $file_name;
echo "<script>console.log('".$target_file."');</script>";
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//echo " vamos a ver que hay aqui " .$target_file;
// Check if pdf already exist
if (file_exists($target_file)) {
$fileErr = "Este documento ya existe.";
$success = false;
}
if ($_FILES["documentPDF"]["size"] > 1000000) {
$fileErr = "El documento es demasiado largo";
$success = false;
}
// Allow certain file formats
if($fileType != "pdf" ) {
$fileErr = "El documento debe estar en formato pdf";
$success = false;
}
// Check if $uploadOk is set to 0 by an error
if ($success == true ) {
if (!move_uploaded_file($_FILES["documentPDF"]["tmp_name"], $target_file)) {
$fileErr ="No se ha podido almacenar el documento ". basename( $_FILES["documentPDF"]["name"]);
$success = false;
}
}
}
}
}
$result="";
// Now we have to prepare the data for the sql operation
if( $action == 'add' && $success ){
$name = test_input($_POST['name']);
$date = $date;
$type = test_input($_POST['type']);
$path = $file_name;
$id = $type ." ". $date . " " . $path ;
//Create $sql sentence
include 'dbh.inc.php';
$sql = "INSERT INTO `shareholders_documents`(`id`, `name`, `date`, `type`, `path`) VALUES ('".$id."','".$name."',STR_TO_DATE('".$date."', '%d-%m-%Y %H:%i'),'".$type."','".$path."')";
$sqlResult = $conn->query($sql);
$message= "";
if($conn->error){
$message = $conn->error;
$success = false;
}
//Sending email
if ($success){
$result='<div class="alert alert-success margin-top-big">El documento se ha subido correctamente'.$name." ".$date." ".$type." ". $path. "\n" . $sql. '</div>';
}
else{
$result = '<div class="alert alert-danger margin-top-big">Algo ha fallado y el documento no se ha podido subir ' . $message . '</div>';
if(empty($fileErr)){ //If we cannot insert the document we must delete the file
unlink($target_file);
}
}
}
//Cleaning global array $_POST
$_POST = array();
$_FILE = array();
//
// Form validation
//
$div = ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" action="" enctype="multipart/form-data">
<input class="col-xs-12 form-control addingForm ' ;
if( !empty($nameErr) ) {
$div .= "boxError alert-danger " ;
}
$div.= '" value="';
if( !$success ) {
$div .= $name;
}
$div .='" type="text" name="name" placeholder=" ';
if( !empty($nameErr) ) {
$div .= $nameErr;
}else{
$div .= "nombre";
}
$div .= '" required>
<input class="col-xs-12 form-control addingForm ';
if( !empty($dateErr) ) {
$div .= "boxError alert-danger " ;
}
$div .=' " value="';
if( !$success ) {
$div .= $date;
}
$div .= '" type="text" name="date" placeholder=" ';
if( !empty($dateErr) ) {
$div.= $dateErr;
}else{
$div.= "fecha (Ejemplo de formato: 31/10/2017 17:54)";
}
$div .='" required>
<select class="col-xs-12 form-control addingForm ';
if( !empty($typeErr) ) {
$div .= "boxError alert-danger" ;
}
$div.= ' " name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12 addingForm" type="file" id="documentPDF" name="documentPDF" accept="application/pdf" >
<span class="error col-xs-12" style="float:left">';
if( !empty($fileErr) ) {
$div .= "* ";
$div .= $fileErr;
}
$div .= ' </span>
<button class="btn btn-default buttonFunctionality" type="submit" name="add" value="add">Añadir</button>
';
if ( !empty($result) ){
$div.= $result;
}
$div .='
</form>
</div>
</div>';
echo $div ;
}
So this is the way I got to solve it, I know it now very complicated for I am sure a lot of beginers get stack in it as I got. I hope I will save some time to anyone.
Thanks to the people who has try to help me.

auto generate text field value when dropdown is select

hello i'm using Yii framework and oracle database. i need some help to solve this problem. i've a form for sending an email. my form looks like this
email desc: _______|v| (dropdown value form database)
email subject : _________ (this field will automatically filled with data of selected email subject)
email body : _______ (this field will automatically filled with data of selected email subject)
my table:
email_desc| subject| body_email
payment1 | payment for house rent | address: **** city: jakarta
ex: i choose email_desc as payment1, email subject will automatically filled as "payment for rent" and email body will automatically filled as address: **** city: jakarta
here is my form
<div class="control-group">
<?php echo $form->labelEx($model,'EMAIL_DESC', array('class'=>'control-label')); ?>
<?php echo $form->dropDownlist($model,'EMAIL_DESC',
(CHtml::listData (TrnProjImplement::model()->getList(),'EMAIL_DESC','EMAIL_DESC')),
array(
'empty'=>'--Pilih salah satu--',
'value'=>$model->EMAIL_DESC,
'id'=>"dropDown",
'ajax'=>array(
'type'=>'GET',
'url'=>CController::createUrl('email/field'),
'update'=>'#subject',
'data'=>array('EMAIL_DESC'=>'js: this.value'),
),
));
?>
<span class="help-inline text-error"><?php echo $form->error($model,'EMAIL_DESC'); ?></span>
</div>
<div class="control-group">
<?php echo $form->labelEx($model,'SUBJECT', array('class'=>'control-label')); ?>
<?php echo $form->textField($model,'SUBJECT',array('size'=>60,'maxlength'=>100, 'style'=>'width:600px', 'id'=>"subject"));?>
<?php //echo CHtml::activeTextField($model, 'SUBJECT',
// array(
// 'ajax'=>array(
// 'type'=>'POST',
// 'url'=>Yii::app()->createUrl('email/create'),
// 'id'=>'subject',
// ),
// ));
?>
<span class="help-inline text-error"><?php echo $form->error($model,'SUBJECT'); ?></span>
</div>
<!--<div class="control-group" id="body-email">-->
<div class="control-group">
<?php echo $form->labelEx($model,'BODY_EMAIL', array('class'=>'control-label')); ?>
<?php echo $form->textArea($model,'BODY_EMAIL',array('size'=>1000,'maxlength'=>1000,'style'=>'height:200px; width:600px;', 'id'=>"body-email")); ?>
<span class="help-inline text-error"><?php echo $form->error($model,'BODY_EMAIL'); ?></span>
</div>
javascript
<script>
function insertField(){
var desc = document.getElementById("dropDown").value;
var subj = document.getElementById("subject").value;
var body = document.getElementById("body-email").value;
$.ajax({
type : "POST",
url : "<?php echo Yii::app()->createUrl("emaildetail/field"); ?>",
data : {
"desc" : desc,
"subj" : subj,
"body" : body,
},
success: function (){
alert('asd');
},
});
</script>
my controller
public function actionField(){
if(isset($_POST['desc'])){
$connection=Yii::app()->db;
$desc = Yii::app()->request->getPost('desc');
$subj = Yii::app()->request->getPost('subj');
$body = Yii::app()->request->getPost('body');
$sql = 'SELECT SUBJECT FROM EMAIL_DETAIL WHERE EMAIL_DESC = $desc';
$sql2 = 'SELECT BODY_EMAIL FROM EMAIL_DETAIL WHERE EMAIL_DESC = $desc';
$model2 = EMAIL_DETAIL::model()->findByAttributes(array('EMAIL_BODY'=>$desc));
if(isset($desc)){
$subj = $model->SUBJECT;
$body = $model->EMAIL_BODY;
}
}
}
i could get the value of email_desc but i still cant automatically fill other field
You can change your code as following solution.
Please change your form as below code :
<div class="control-group">
<?php echo $form->labelEx($model,'EMAIL_DESC', array('class'=>'control-label')); ?>
<?php echo $form->dropDownlist($model,'EMAIL_DESC',
(CHtml::listData (TrnProjImplement::model()->getList(),'EMAIL_DESC','EMAIL_DESC')),
array(
'empty'=>'--Pilih salah satu--',
'value'=>$model->EMAIL_DESC,
'id'=>"dropDown",
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createUrl('email/field'),
'data'=>array('EMAIL_DESC'=>'js: this.value'),
'success'=> 'function(response) {if (response.status == "success") {
$("#SUBJECT").val(response.subj);
$("#BODY_EMAIL").val(response.body);
} else {
$("#SUBJECT").val("");
$("#BODY_EMAIL").val("");
}
}',
'error'=> 'function(){alert("AJAX call error..!!!!!!!!!!");}',
),
));
?>
<span class="help-inline text-error">
<?php echo $form->error($model,'EMAIL_DESC'); ?>
</span>
</div>
<div class="control-group">
<?php echo $form->labelEx($model,'SUBJECT', array('class'=>'control-label')); ?>
<?php echo $form->textField($model,'SUBJECT',array('size'=>60,'maxlength'=>100, 'style'=>'width:600px', 'id'=>"subject"));?>
<span class="help-inline text-error"><?php echo $form->error($model,'SUBJECT'); ?></span>
</div>
<div class="control-group">
<?php echo $form->labelEx($model,'BODY_EMAIL', array('class'=>'control-label')); ?>
<?php echo $form->textArea($model,'BODY_EMAIL',array('size'=>1000,'maxlength'=>1000,'style'=>'height:200px; width:600px;', 'id'=>"body-email")); ?>
<span class="help-inline text-error"><?php echo $form->error($model,'BODY_EMAIL'); ?></span>
</div>
Please change your Controller code :
<?php
public function actionField() {
if (Yii::app()->request->isAjaxRequest){
$desc = Yii::app()->request->getPost('EMAIL_DESC');
$model = EMAIL_DETAIL::model()->findByAttributes(array('EMAIL_BODY' => $desc));
if (!empty($model)) {
$data['status'] = 'success';
$data['subj'] = $model->SUBJECT;
$data['body'] = $model->EMAIL_BODY;
} else {
$data['status'] = 'error';
$data['subj'] = '';
$data['body'] = '';
}
echo json_encode($data);
Yii::app()->end();
} else
throw new CHttpException(400, '404_error_message');
}
?>
I hope this will helps you. Thanks!

two dropdown-boxes on one page without submit

I do have a problem with two dropdown boxes on one page. Cause I have to work without a submit I use the "onblur=document.getElementById.submit" in the "". This works fine but only for one dropdown box. Using the same(equal) code for both forms will result in destroying the entries of form1 when selecting an item in form2 and visa verse.
Form-1:
<form id="formunit" name="formunit" method="post" action="" >
<select name="cbo_unit" required="required" form="formunit" style="width:100pt" onblur="document.getElementById('formunit').submit();">
<option value="0">--select--</option>
<?php
if ($_POST["cbo_unit"] == "MH") {
echo "<option value=\"MH\" selected=\"selected\">Motorhome</option>";
} else {
echo "<option value=\"MH\">Motorhome</option>";
}
if ($_POST["cbo_unit"] == "RT") {
echo "<option value=\"RT\" selected=\"selected\">Racetruck</option>";
} else {
echo "<option value=\"RT\">Racetruck</option>";
}
?>
</select>
<?php
if(isset($_POST['cbo_unit']) && $_POST['cbo_unit'] > '') {
$unit = $_POST['cbo_unit'];
}
?>
</form>
Form-2:
<?php
fc_opendb("1","something",$connect);
$dbtable = "course";
$result = mysqli_query($GLOBALS["connect"],"SELECT * FROM " . $dbtable . " WHERE blocked = 'no' ORDER BY matchcode ASC");
?>
<form id="formcourse" name="formcourse" method="post" action="" >
<select name="cbo_course" required="required" form="formcourse" style="width:130pt" onblur="document.getElementById('formcourse').submit();">
<option value="0">--select--</option>
<?php
while ($row = mysqli_fetch_assoc($result)) {
if ($row['matchcode'] == $_POST['cbo_course']) {
$selected = "selected";
} else {
$selected = "";
}
echo '<option value="' . $row['matchcode'] . '"' . $selected . '>' . utf8_encode($row['name']) . ' - ' . utf8_encode($row['place']) . '</option>'."\n";
}
?>
</select>
<?php
if(isset($_POST['cbo_course']) && $_POST['cbo_course'] > '') {
$course = $_POST['cbo_course'];
}
mysqli_close($GLOBALS["connect"]);
?>
</form>

How to get value from dynamically filled drop down on button click in php

I am stuck in getting value from drop down. Drop down is dynamically filled from sql server database.
Dropdown 1 displays product name and it is dynamically filled.
Dropdown 2 displays environment name and it is filled by HTML.
I am getting value of environment but not product.
Please help me. Thanks
Here is the code:
<form action="" method="post">
//Dropdown 1
<p>Product Name:
<select name="productname">
<option value="">Select</option>
<?php
if( $conn )
{
$sql_dd = "SELECT ProductName from Product";
$stmt = sqlsrv_query( $conn, $sql_dd );
if( $stmt === false) {die( print_r( sqlsrv_errors(), true) );}
$rows = sqlsrv_has_rows( $stmt );
if ($rows === false)
echo "There is no data. <br />";
else
{ while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
echo "<option value=''>".$row['ProductName']."</option>";
}
}
?>
//Dropdown 2
Client Type:
<select name="environment" style="width: 10%;">
<option value="">Select</option>
<option value="en1">en1</option>
<option value="en2">en2</option>
<option value="en3">en3</option>
</select> 
<input type="submit" class="theme-btn" value="Search" name="submit"/>
<?php
if(isset($_POST['submit']) )
{
$productname = $_POST['productname'];
$environment= $_POST['environment'];
echo "productname: ".$productname." environment: ".$environment;
}?>
The value is not added
this:
echo "<option value=''>".$row['ProductName']."</option>";
should be
echo "<option value='" . $row['ProductName'] . "'>". $row['ProductName'] ."</option>";

Redirect on another page after form submission

I have 4 pages: register.php, view.php , edit.php and display.php
On view.php i have a form that displays all data from database.
I have a search box, results of which are displayed in display.php(it displays just one row from database).
In display php i have a form with edit button for the entry. The edit button redirect me to edit.php where i can change my data. When i save, it redirect me on view.php but i want in display php with saved values of edited entry.
I tried in but it desnt work.
The second problem i have here is to keep in edit.php the dropdown option that i selected in in register.php
I;m new in programation and i hope someone will help me in this problem. THX for help.
My pages:
DISPLAY.PHP
<?php
include('connect-db.php');
$client = $_POST['client'];
$contract = $_POST['contract'];
if(
$contract = $_POST['contract'] )
{$query = "select * from users where contract = '$contract'"; }
else{
$query= "select * from users where client = '$client'";
}
$result = mysql_query($query);
echo "<table>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
// echo out the contents of each row into a table
echo '<label>Contract</label><input readonly="true" value=' . $row['contract'] . '>';
echo '<label>Client</label><input readonly="true" type="text" value="' . $row['client'] . '">';
echo '<label>Step</label><input type="text" readonly="true" value=' . $row['Step'] . '>';
echo '<br><input type="submit"value="Change">';
echo '<br>';
echo "</table>";
}
?>
EDIT.PHP
<?php
function renderForm($contract, $client, $step
{
?>
<!DOCTYPE html>
<body>
<form id="base" name="base" method="post" action="">
<input data-validate="number" value="<?php echo $contract; ?>" readonly="true" id="contract">
<input data-validate="text" value="<?php echo $client; ?>" id="client">
<select name="step">
<option value="option1">Option1</option>
<option value="option2">Option2</option>
</select>
<input type="submit" value="Change">
</form>
</body>
</html>
<?php
}
include('connect-db.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['contract']))
{
$contract = mysql_real_escape_string(htmlspecialchars($_POST['contract']));
$client = mysql_real_escape_string(htmlspecialchars($_POST['client']));
$step = mysql_real_escape_string(htmlspecialchars($_POST['step']));
if ($contract == '' || $client == '' )
{
$error = 'ERROR: Please fill in all required fields!';
renderForm($contract, $client, $step, $error);
}
else
{
mysql_query("UPDATE users SET
contract='$contract', client='$client', step='$step', WHERE contract='$contract'")
or die(mysql_error());
header("Location: view.php");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['contract']) && is_numeric($_GET['contract']) && $_GET['contract'] > 0)
{
$contract = $_GET['contract'];
$result = mysql_query("SELECT * FROM users WHERE contract=$contract")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$contract = $row['contract'];
$client = $row['client'];
$step = $row['step'];
renderForm($contract, $client, $step, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>
VIEW.PHP
<!DOCTYPE html>
<html>
<?php
include('connect-db.php');
$sql="SELECT * FROM users";
$result =mysql_query($sql);
{
?>
<table>
<thead>
<tr>
<th span style="font-weight: normal;">Contrat</th>
<th span style="font-weight: normal;">Client</th>
<th span style="font-weight: normal;">Step</th>
</tr>
</thead>
<?php
}
while ($data=mysql_fetch_assoc($result)){
?>
<tbody>
<tr>
<td><?php echo $data['contract'] ?></td>
<td><?php echo $data['client'] ?></td>
<td><?php echo $data['step'] ?></td>
<td><input type="button" value="Change"></td>
</tr> <?php } ?>
</tbody>
</table>
</body>
</html>
REGISTER.PHP
<!DOCTYPE html>
<html>
<form id="base" method="post" action="insert.php">
<br>
<br>
<input data-validate="number" id="contract" name="contract">
<input data-validate="text" id="client" name="client">
<select name="step">
<option value="option1">OPTION1</option>
<option value="option2">OPTION2</option>
</select>
<button data-validate="submit">Register</button>
</form>
</body>
</html>
use this instead of your edit.php
<?php
function renderForm($contract, $client, $step
{
?>
<!DOCTYPE html>
<body>
<form id="base" name="base" method="post" action="">
<input data-validate="number" value="<?php echo $contract; ?>" readonly="true" id="contract">
<input data-validate="text" value="<?php echo $client; ?>" id="client">
<select name="step">
<option value="option1">Option1</option>
<option value="option2">Option2</option>
</select>
<input type="submit" value="Change">
</form>
</body>
</html>
<?php
}
include('connect-db.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['contract']))
{
$contract = mysql_real_escape_string(htmlspecialchars($_POST['contract']));
$client = mysql_real_escape_string(htmlspecialchars($_POST['client']));
$step = mysql_real_escape_string(htmlspecialchars($_POST['step']));
if ($contract == '' || $client == '' )
{
$error = 'ERROR: Please fill in all required fields!';
renderForm($contract, $client, $step, $error);
}
else
{
mysql_query("UPDATE users SET
contract='$contract', client='$client', step='$step', WHERE contract='$contract'")
or die(mysql_error());
header("Location:display.php");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['contract']) && is_numeric($_GET['contract']) && $_GET['contract'] > 0)
{
$contract = $_GET['contract'];
$result = mysql_query("SELECT * FROM users WHERE contract=$contract")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$contract = $row['baza_contract'];
$client = $row['baza_client'];
$step = $row['step'];
renderForm($contract, $client, $step, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>

Categories

Resources