echo php form validation with ajax - javascript

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.

Related

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!

JavaScript error and database update

I have a problem with my database and doing the update of it. I have a database table stock with 5 columns (stock_id, p_id, brand_id, cat_id, availability). I want to do an update from the frontend. So when the popup show up and I fill in the form, UPDATE doesn't work. I have 3 files. First one stock.php that read database and works fine. the seconf one that open if you click edit looks like this:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM stock WHERE stock_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
$brand_id = $row['brand_id'];
$p_id = $row['p_id'];
?>
<form method="post" name="form">
<input id="stock_id" name="stock_id" type="hidden" value="<?php echo $row['stock_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND</label>
<select id="brand" name="brand" class="switchable form-control">
<?php
$qex = "SELECT * FROM brand";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['brand_id']; ?>"<?php
if ($brand_id == $rowex['brand_id'])
echo 'selected'; ?> class="brand_<?php echo $rowex['cat_id'];?>"><?php echo $rowex['brand_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">PRODUCT NAME</label>
<select id="product" name="product" class="switchable form-control">
<?php
$qex = "SELECT * FROM product";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['product_id']; ?>"<?php
if ($product_id == $rowex['product_id'])
echo 'selected'; ?> class="product_<?php echo $rowex['brand_id'];?>"><?php echo $rowex['product_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">IN STOCK</label>
<input type="number" id="availability" name="availability" value="<?php echo $row['availability'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var stock_id = $("#stock_id").val();
var category = $('select[name="category"]').val()
var brand = $('select[name="brand"]').val()
var product = $('select[name="product"]').val()
var availability = $("#availability").val();
var dataString =
'stock_id='+ stock_id +
'&brand=' + brand +
'&category=' + category +
'&product=' + product +
'&availability=' + availability
;
if(
stock_id=='' ||
brand=='' ||
category=='' ||
product=='' ||
availability==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-stock.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
$("#category").change(function () {
if ($(this).data('options') == undefined) {
$(this).data('options', $('select.switchable option').clone());
}
var id = $(this).val();
var that = this;
$("select.switchable").each(function () {
var thisname = $(this).attr('name');
var theseoptions = $(that).data('options').filter('.' + thisname + '_' + id);
$(this).html(theseoptions);
});
});
//then fire it off once to display the correct elements
$('#category').trigger('change');
});/** Document Ready Functions END **/
</script>
<?php } ?>
This is my code for update-stock.php that supposed to be updating the database:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$stock_id = $_POST['stock_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$availability = $_POST['availability'];
$update = array(
'p_id' => $product,
'brand_id' => $brand,
'cat_id' => $cat,
'availability' => $availability
);
$where_clause = array(
'stock_id' => $stock_id
);
$updated = $database->update( 'stock', $update, $where_clause, 1 );
}
?>
I have a 2 problems.
Update doesn't work at all. I am just getting the message Please Enter Valid Data
My form doesn't show up the correct value of the PRODUCT NAME. Example: In the database and my main table that read information from database product name is 2.1.1 but when I click on edit and open my pop-up form that show up 2.1.3 for example.
Thank you so much in advance for your help.
This one works PERFECT fetch_brand.php:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM brand WHERE brand_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
?>
<form method="post" name="form">
<input id="brand_id" name="brand_id" type="hidden" value="<?php echo $row['brand_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND NAME</label>
<input type="text" id="brand_name" name="brand_name" value="<?php echo $row['brand_name'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var brand_id = $("#brand_id").val();
var brand_name = $("#brand_name").val();
var category = $('select[name="category"]').val()
var dataString =
'brand_id='+ brand_id +
'&brand_name=' + brand_name +
'&category=' + category
;
if(
brand_id=='' ||
brand_name=='' ||
category==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-brand.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
});/** Document Ready Functions END **/
</script>
<?php } ?>
update-product.php :
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$p_id = $_POST['p_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$update = array(
'product_name' => $product,
'brand_id' => $brand,
'cat_id' => $cat
);
$where_clause = array(
'p_id' => $p_id
);
$updated = $database->update( 'product', $update, $where_clause, 1 );
}
?>
This one works excellent! So I am pretty sure that I made a mistake in my code for the stock.

PHP forms through loop doesn't send specific session against checked radio button

I am working on an e-testing system in which when a candidate login the test for which he/she was register will be shown to him/her.
I am getting the specific test through session to show the questions containing in that test. This was successfully done with the help of some "if" checks and two while loops(1 for questions and 2nd for answers against that question) having the form of radio buttons for selecting an answer.
Now each time when loop execute it create a form for single question and its answer, that way for multiple questions it results in multiple.
I am getting the checked radio buttons through ajax and posting it to another php file but I need a question id of checked answer as well to be passed to the 2nd php file
I used session but it only get the id of 1st checked and not for the others.
The 2nd php file name is answers.php for the time being i just want to post and get all values and session in answers.php file.
the main problem is with $_SESSION ['qid'] = $id; session
Note: i have used unset and destroy session to free the session and tried to re start it but i am field to do so..
<?php
include ("connection.php");
// $mysql_row = '';
$query_run = null;
$test = $_SESSION ['id'];
var_dump ( $_SESSION ['id'] );
$query1 = "SELECT * FROM question where testid = '" . $_SESSION ['id'] . "'";
if ($query_run = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
print "No result";
} else {
// echo'<form action="ss.php" method="post">';
while ( $mysql_row = mysql_fetch_assoc ( $query_run ) ) {
$id = $mysql_row ['qid'];
$_SESSION ['qid'] = $id;
echo ' <div class="panel-heading" style="background: black; font-weight:bold;">Question </div>';
$data = $mysql_row ['questions'];
?>
<form>
<br>
<div class=" form-control well well-sm">
<?php echo'<div style="font-weight:bold;"> Q: '.$data.' </div> '; ?>
<br>
</div>
<?php
$query1 = "SELECT * FROM `answer` where id='" . $id . "'";
if ($query_run1 = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
} else {
while ( $mysql_row1 = mysql_fetch_assoc ( $query_run1 ) ) {
$data1 = $mysql_row1 ['ans1'];
$data2 = $mysql_row1 ['ans2'];
$data3 = $mysql_row1 ['ans3'];
$data4 = $mysql_row1 ['ans4'];
echo "\n";
?>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option1</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data1' name='opt1' onclick='OnChangeRadio (this)'> $data1<br />";
?>
<br>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option2</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data2' name='opt1' onclick='OnChangeRadio (this)'> $data2<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option3</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data3' name='opt1' onclick='OnChangeRadio (this)'> $data3<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option4</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data4' name='opt1' onclick='OnChangeRadio (this)'> $data4<br />";
// echo'</form>';
?>
</div>
<?php
echo '</form>';
}
}
}
// $view_id1 = $view_id;
// echo $view_id1;
}
}
} else {
print mysql_error ();
}
// unset($_SESSION['qid']);
?>
connection.php
<?php
session_start ();
if (! $_SESSION ['user']) {
header ( "Location: index.php" );
// redirect to main page to secure the welcome
// page without login access.
}

How to separate data and register it in a database

I'm trying to separate the data that I get here and trying to register it in the database.
I get the data with a form that looks like this.
var max_input_fields=10;
var delimiter='|';
function http( data, callback ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 ) callback.call( this, xhr.response );
};
xhr.open( 'POST', document.location.href, true );
xhr.send( data );
}
function cbhttp(r){
document.querySelectorAll('output')[0].innerHTML=r
}
function bindEvents(){
var oBttnAdd=document.getElementById('bttnadd');
var oBttnSub=document.getElementById('bttnsub');
var oForm=document.getElementById('dynelems');
var oParent=document.getElementById('loopdiv');
oBttnSub.onclick=function(e){
/* scan the form and get values from all elements ( including dynamcially added ) and submit the form via xhr */
var col=oForm.querySelectorAll('input[type="text"],textarea,select');
var data=new FormData();
data.append('delimiter',delimiter);
for( var n in col ) if( col[n] && col[n].nodeType==1 ) {
data.append( col[n].name, col[n].value.replace( delimiter, '' ) + delimiter );
}
http.call( this, data, cbhttp );
};
oBttnAdd.onclick=function(e){
/* Add new rows based upon selected option from dropdown menu */
var col=oParent.querySelectorAll('section[data-id]');
var length=col.length;
if( length < max_input_fields ){
var newid=parseInt( col[ length-1 ].dataset.id ) + 1;
var clone=oParent.childNodes[1].cloneNode( true );
clone.dataset.id=newid;
/* Set new name for the textarea */
clone.childNodes[3].childNodes[1].name='videolink'+newid;
oParent.appendChild( clone );
}
}
}
document.addEventListener('DOMContentLoaded', bindEvents,false);
<form action="adddilemman.php" id="dynelems" method="post" enctype="multipart/form-data">
<br>
<div id='loopdiv'>
<?php
/* Data-id is used by js to determine next suitable id */
echo "
<section data-id=1>
<h2>Dilemma</h2>
<div>Video länk:<br><textarea rows='1' cols='40' name='videolink1'></textarea></div>";
for( $i=1; $i <= 4; $i++ ){
/* Add four text fields and four select menus */
echo "
<div>
Answer: <input type='text' name='answer{$i}[]'/>
<select name='options{$i}[]'>";
/* Add options to each select menu */
for( $j=1; $j <= 10; $j++ ){
echo "<option value={$j}>{$j}";
}
/* Close each nested div & select menu */
echo "
</select>
</div>";
}
/* Close initial section */
echo "
</section>";
?>
</div>
<div class='input_fields_wrap'>
<div></div>
</div>
<input id='bttnadd' type='button' name='add_field_button' value='Lägg till fler svar'/>
<input id='bttnsub' type='submit' name='sub' value='Submit'/>
</form>
<output></output>
I'm using "adddilemman.php" to show the data just to see if its working and its working. But I have now idea how to register this data in the database. PS I want to register it in two different tables (textarea in a table and answers in another table)
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* This is here only to simplify development and display here */
$delimiter=isset( $_POST['delimiter'] ) ? $_POST['delimiter'] : '|';
/* process form submission: for testing purposes just echo out data sent */
foreach( $_POST as $field => $value ) {
if( $field!='delimiter' ){
if( is_array( $value ) ) echo 'Array values: '.$field.'='.rtrim( str_replace( $delimiter, ',', implode( ' ', $value ) ), ',' ).'<br />';
else echo 'String value: '.$field.'='.trim( str_replace( $delimiter, '', $value ) ).'<br />';
}
}
exit();
}
?>
Any recommendations how I can separate this data and register it in the database?
You would want to setup the form like so:
<textarea rows='1' cols='40' name='videolink1'><?php echo isset($_POST['videolink1'])?$_POST['videolink1']:""; ?></textarea>
<?php
for( $i=1; $i < 5; $i++ ){
/* Add four text fields and four select menus */
?>
<div>
<label>Answer:</label>
<input type='text' name='answer[<?php echo $i; ?>]' value="<?php echo isset($answer[$i])?$answer[$i]:''; ?>" />
<select name='options[<?php echo $i; ?>]'>
<?php
for( $j=1; $j <= 10; $j++ ){
if($options[$i] == $j){
echo "\t\t\t\t\t<option selected='selected' value={$j}>{$j}</option>\r\n";
} else {
echo "\t\t\t\t\t<option value={$j}>{$j}</option>\r\n";
}
}
?>
</select>
</div>
<?php
}
?>
I would prepare the post data like so:
<?php
$vidlink = "";
$answers = array();
$options = array();
if(isset($_POST['sub'])){
$vidlink = htmlentities($_POST['videolink1']);
for($i=1;$i<=count($_POST['answer']);$i++){
$answer[$i] = $_POST['answer'][$i];
$options[$i] = $_POST['options'][$i];
}
}
?>
This will place the content of the answers and options in their own arrays but with the same indexes. You can loop and place them in the DB any way you like. Here is an example:
$con = mysqli_connect("localhost", "root", "", "wildfire");
if($con === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
for($i=1;$i<=$count($answer);$i++){
if ($stmt = mysqli_prepare($con, "INSERT INTO answer_det ('aid', 'answer', 'points') VALUES (?, ?, ? )")) {
mysqli_stmt_bind_param($stmt, "isi", $i, $answer[$i], $options[$i]);
mysqli_stmt_execute($stmt);
}
}
Here is all the code I used for testing on phpfiddle.org:
<?php
$vidlink = "";
$answers = array();
$options = array();
if(isset($_POST['sub'])){
$vidlink = htmlentities($_POST['videolink1']);
for($i=1;$i<=count($_POST['answer']);$i++){
$answer[$i] = $_POST['answer'][$i];
$options[$i] = $_POST['options'][$i];
}
}
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="dynelems" method="post" enctype="multipart/form-data">
<div id='loopdiv'>
<section data-id=1>
<h2>
Dilemma
</h2>
<div>
Video länk:
<br />
<textarea rows='1' cols='40' name='videolink1'><?php echo isset($_POST['videolink1'])?$_POST['videolink1']:""; ?></textarea>
</div>
<?php
for( $i=1; $i < 5; $i++ ){
/* Add four text fields and four select menus */
?>
<div>
<label>Answer:</label>
<input type='text' name='answer[<?php echo $i; ?>]' value="<?php echo isset($answer[$i])?$answer[$i]:''; ?>" />
<select name='options[<?php echo $i; ?>]'>
<?php
for( $j=1; $j <= 10; $j++ ){
if($options[$i] == $j){
echo "\t\t\t\t\t<option selected='selected' value={$j}>{$j}</option>\r\n";
} else {
echo "\t\t\t\t\t<option value={$j}>{$j}</option>\r\n";
}
}
?>
</select>
</div>
<?php
}
?>
</section>
</div>
<div class='input_fields_wrap'>
<div>
</div>
</div>
<input id='bttnadd' type='button' name='add_field_button' value='Lägg till fler svar'/>
<input id='bttnsub' type='submit' name='sub' value='Submit'/>
</form>
<output>
<?php
if(isset($_POST['sub'])){
htmlentities(var_export($_POST));
var_export($answer);
var_export($options);
}
</output>
</html>

How to retain dropdown value after the page is reloaded?

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");

Categories

Resources