I want to change the div's id intFrom. Content after inserting data to the database, I want the code not just echo ¡Enhorabuena!...
But replace the form with ¡Enhorabuena! I maybe, I could replace the form using AJAX.
Here is the code:
HTML
<form method="post" action="">
<div>
<select value="genero" name="genderselect" id="genero" required="required" autofocus="autofocus">
<option value="none" selected>- Selecciona Género - </option>
<option value="Mujer">Mujer</option>
<option value="Hombre">Hombre</option>
</select>
<input type="text" id="name" name="name" value="" placeholder="Nombre completo" required="required" autofocus="autofocus" />
<input type="email" id="email" name="email" value="" placeholder="Correo electrónico" required="required" />
</div>
<div>
<div class="infForm img">
<img src="http://www.miraqueguapa.com/Landings/General/img/biotherm.png" alt="Imagen Crema Aquasource Biotherm" class="biotherm">
</div>
<div class="infForm text">
<div class="legal">
<input type="checkbox" id="cblegales" value="1" name="cblegales" required="required" autofocus="autofocus">
<p>He leído y acepto la <a class="enlace_pp" href="http://www.miraqueguapa.com/content/5-privacidad-proteccion-datos" target="_blank">política de privacidad</a></p>
</div>
<input type="submit" value="ENVIAR DATOS" name="submit_form" style=" background-color: #DF2848;border: none;border-radius: 0px;color: white;width: 200px;float: right;padding-left: 50px;cursor: pointer;margin-top: -5px;" />
</div>
</div>
</form>
</div>
PHP
<?php
if (isset($_POST['submit_form'])) {
include 'connection.php';
$name=$_POST["name"];
$email=$_POST["email"];
$gender=$_POST["genderselect"];
if($gender=="none"){
echo"</br>";
echo"por favor selecciona nuestro género";
$link = null;
}
else{
$i=0;
$statement = $link->prepare("select email from webform where email = :email");
$statement->execute(array(':email' => "$email"));
$row = $statement->fetchAll();
foreach($row as $key) {
$i=$i+1;
}
if ($i !=0) {
echo" Este correo electrónico ya está registrado";
$link = null;
}
else{
$statement = $link->prepare("INSERT INTO webform(name, email, gender)
VALUES(:name, :email, :gender)");
$statement->execute(array(
"name" => "$name",
"email" => "$email",
"gender" => "$gender"
));
$link = null;
echo"¡Enhorabuena!"."<br/>";
echo"Tus datos se han enviado correctamente. A partir de ahora recibirás cada semana las últimas novedades y las mejores ofertas en Cosmética de las marcas más prestigiosas del mercado.";
}}}
?>
You need to add simple if else statement.
if (isset($_POST['submit_form'])) {
// Your code after form get submitted.
}
else {
// Show default form.
}
Just load your HMTL Code in to your PHP as a kind of "Template" with file_get_contents(__DIR__ . "Path/To/Your.html"); in to a variable and do a simple str_replace('id="your_element_id"', 'id="replace_id"', $template_variable); and echo your Template after if you just want to replace an ID.
If you want to change something within the Form, do it as i said above with str_replace('tag_you_are_looking_for', 'should_be_replaced_with', $template_variable);
Related
I'm currently working on a school project and i'm trying to upload a "post" of a recipe. this includes image, title, instructions,ingredients and also 1 or multiple categories.
all of them insert fine and well. the only issue is with the categories. It only inserts 1 category even if I select multiple checkboxes.
It's supossed to insert every checkbox into a new row in the database.
My DAO
public function insertCategory($data, $title) {
if (empty($errors)) {
$sql = "INSERT INTO `recipes_categories` (`category_id`, `recipe_id`) VALUES(:category_id,:recipe_id);";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':category_id', $data['category_id']);
$stmt->bindValue(':recipe_id', $title['id']);
if ($stmt->execute()) {
return $this->selectcategoryById($this->pdo->lastInsertId());
}
}
return false;
}
My Controller (relevant parts)
public function upload() {
// variabele om foutmelding bij te houden
$error = '';
// controleer of er iets in de $_POST zit
if(!empty($_POST['action'])){
// controleer of het wel om het juiste formulier gaat
if($_POST['action'] == 'add-image') {
// controleren of er een bestand werd geselecteerd
if (empty($_FILES['image']) || !empty($_FILES['image']['error'])) {
$error = 'Gelieve een bestand te selecteren';
}
if(empty($error)){
// controleer of het een afbeelding is van het type jpg, png of gif
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
if(!in_array($_FILES['image']['type'], $whitelist_type)){
$error = 'Gelieve een jpeg, png of gif te selecteren';
}
}
if(empty($error)){
// controleer de afmetingen van het bestand: pas deze gerust aan voor je eigen project
// width: 270
// height: 480
$size = getimagesize($_FILES['image']['tmp_name']);
if ($size[0] < 100 || $size[1] < 100) {
$error = 'De afbeelding moet minimum 100x100 pixels groot zijn';
}
}
if(empty($error)){
// map met een random naam aanmaken voor de upload: redelijk zeker dat er geen conflict is met andere uploads
$projectFolder = realpath(__DIR__);
$targetFolder = $projectFolder . '/../assets/ads';
$targetFolder = tempnam($targetFolder, '');
unlink($targetFolder);
mkdir($targetFolder, 0777, true);
$targetFileName = $targetFolder . '/' . $_FILES['image']['name'];
// via de functie _resizeAndCrop() de afbeelding croppen en resizen tot de gevraagde afmeting
// pas gerust aan in je eigen project
$this->_resizeAndCrop($_FILES['image']['tmp_name'], $targetFileName, 100, 100);
$relativeFileName = substr($targetFileName, 1 + strlen($projectFolder));
$data = array(
'image' => $relativeFileName,
'title' => $_POST['title'],
'instructions' => $_POST['stappenplan'],
'description' => $_POST['ingredienten'],
'category_id' => $_POST['category'],
);
// TODO: schrijf de afbeelding weg naar de database op basis van de array $data
if (!empty($_POST['action'])) {
if ($_POST['action'] == 'add-image') {
// array met data invullen
$data = array(
'path' => '/' . $relativeFileName,
'title' => $_POST['title'],
'instructions' => $_POST['stappenplan'],
'description' => $_POST['ingredienten'],
'category_id' => $_POST['category'],
);
// aanspreken van de DAO
$insertImage = $this->uploadDAO->insertImage($data);
$title = $this->uploadDAO->ImageInsterId($data);
$this->set('title', $title);
$ingredientsArray = explode( ',', $data['description'] );
foreach($ingredientsArray as $ingredient){
$insertIngredient = $this->uploadDAO->insertIngredients($ingredient , $title);
}
$insertCategory = $this->uploadDAO->insertCategory($data, $title);
// TODO 2: zorg dat de variabele $error getoond wordt indien er iets fout gegaan is
if (!$insertImage) {
$errors = $this->uploadDAO->validate($data);
$this->set('errors', $errors);
} else {
$_SESSION['info'] = 'Thank you for adding a Post!';
header('Location: index.php?page=detail&id='. $title['id']);
exit();
}
}
}
}
}
}
There is some code here for the image upload too, but it isn't relevant since that is working.
My HTML
<span class="error"><?php if(!empty($error)){ echo $error;} ?></span>
<section class="upload_box">
<h1 class="hidden">upload-form</h1>
<form method="post" action="index.php?page=upload" enctype="multipart/form-data" class="form__box">
<input type="hidden" name="action" value="add-image" />
<div class="form-field">
<label class="upload__title form_container">Kies een afbeelding
<span class="error"><?php if(!empty($errors['title'])){ echo $errors['title'];}?></span>
<input type="file" name="image" accept="image/png, image/jpeg, image/gif" required class="upload__button filter__submit input">
</label>
</div>
<div class="form-field">
<label class="upload__title form_container">Titel
<span class="error"><?php
if(!empty($errors['title'])){
echo $errors['title'];} ?></span>
<input type="text" name="title" required class="upload__title form_field input">
</label>
</div>
<div class="form-field">
<label class="upload__title form_container">Stappenplan
<span class="error"><?php if(!empty($errors['instructions'])){ echo $errors['instructions'];} ?></span>
<textarea name="stappenplan" id="stappenplan" cols="50" rows="5" required class="form_field upload__title input"></textarea>
</label>
</div>
<div class="form-field">
<label class="upload__title form_container">Ingredienten
<span class="error"><?php if(!empty($errors['description'])){ echo $errors['description '];} ?></span>
<input type="text" TextMode="MultiLine" name="ingredienten" maxlength="255" required class="form_field upload__title input" id="ingredienten">
</label>
</div>
<div class="category_container">
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="pasta" name="category" value="1">
Pasta</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="veggie" name="category" value="2">
Veggie</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="vlees" name="category" value="3">
Vlees</label>
</div>
<div class="form-field">
<input type="submit" value="uploaden" class="filter__button filter__submit">
<input type="reset" value="wissen" class="filter__button filter__submit">
</div>
</form>
</section>
<script src="js/validate.js"></script>
What I do know:
I know the recipe_id isn't an issue. I use the same for other SQL inserts.
I don't want an explode() or implode() as they don't work in this case.
Tried several foreaches but haven't gotten it to work, just yet.
it's also nothing to do with brackets or comma's or whatever.
It's just the insert only doing it once while I have 2 checkbox values. and I don't know how to make it loop over both or all 3 when all 3 are selected
<div class="category_container">
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="pasta" name="category[]" value="1">
Pasta</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="veggie" name="category[]" value="2">
Veggie</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="vlees" name="category[]" value="3">
Vlees</label>
</div>
You need to use category[], rather than just category to send multiple values in form submit.
Now, you can fetch the values of categories
$categories = (is_array($_POST['category'])) ? $_POST['category'] : [];
I have assigned categories a default value if there is no checkbox selected.
Then use implode function of php:
$categories_string = implode(',', $categories);
or use a foreach loop based on how you want to save in your database table:
foreach ($category as $category)
{
//use each category
}
by means of an if attempt that can not be created two records with the same name, it does not work and you can create a record with a dupiclate name
this is the controller
include_once 'model/solucion.php';
public function Guardar()
{
$this->model->Duplicado($_POST['Nombre']);
$name = $this->model->resultado2['Nombre'];
if($name == $_POST['Nombre']){
die("No se puede crear una solucion con el mismo nombre");
}else{
$solucion = new solucion();
$solucion->id = $_REQUEST['id'];
$solucion->Nombre = $_REQUEST['Nombre'];
$solucion->Tipo = $_REQUEST['Tipo'];
$solucion->Descripcion = $_REQUEST['Descripcion'];
$solucion->Pagina = $_FILES['Pagina']['name'];
}
header("Location: index.php");
}
this is the model
public $resultado2;
public function Duplicado($Nombre)
{
try {
$stm = $this->pdo->prepare("SELECT * FROM fallas WHERE Nombre = '$Nombre'");
$stm->execute();
$res=$stm->fetch(PDO::FETCH_ASSOC);
$this->resultado2 = array();
$i = 0;
foreach ($res as $row)
{
$this->resultado2[$i]['id'] = $row['id'];
$this->resultado2[$i]['Nombre'] = $row['Nombre'];
$this->resultado2[$i]['Tipo'] = $row['Tipo'];
$this->resultado2[$i]['Descripcion'] = $row['Descripcion'];
$this->resultado2[$i]['Pagina'] = $row['Pagina'];
$i++;
}
} catch (Exception $ex) {
die($e->getMessage());
}
}
this is the view
<ol class="breadcrumb">
<li>Inicio</li>
<li class="active"><?php echo $solucion->id != null ?
$solucion->Nombre : 'Nueva Solución'; ?></li>
</ol>
<form id="frm-alumno" action="?c=solucion&a=Guardar" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo $solucion->id; ?>" />
<div class="form-group">
<label>Nombre</label>
<input type="text" name="Nombre" value="<?php echo $solucion->Nombre; ?>" class="form-control" placeholder="Ingrese su nombre" required>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Tipo de fallo</label>
<select class="form-control" id="exampleFormControlSelect1" name="Tipo" value="<?php echo $solucion->Tipo; ?>">
<option value="software">software</option>
<option value="hardware">hardware</option>
<option value="red">red</option>
</select>
</div>
<div class="form-group">
<label>Descripcion</label>
<textarea type="text" name="Descripcion" value="<?php echo $solucion->Descripcion; ?>" class="form-control" rows="10" cols="40" required>
</textarea>
</div>
<div class="form-group">
<label>Pagina.php</label>
<input type="file" name="Pagina" value="<?php echo $solucion->Pagina; ?>" >
</div>
<div class="form-group">
<label >Imagenes</label>
<input type="file" class="form-control" id="archivo[]" name="archivo[]" multiple="" >
</div>
<hr />
<br>
<div class="text-right">
<button class="btn btn-success">Guardar</button>
</div>
What do I have to change in the controller to avoid creating duplicate records with the same name?
You need to pass the array and check whether this is empty or not . Check below for the code and run it and let me know if you get any error .
public function Duplicado($Nombre)
{
try{
$stm = $this->pdo->prepare("SELECT * FROM fallas WHERE Nombre = '$Nombre'");
$stm->execute();
$res=$stm->fetch(PDO::FETCH_ASSOC);
return $res;
}catch (Exception $ex) {
die($e->getMessage());
}
}
include_once 'model/solucion.php';
public function Guardar()
{
$name = $this->model->Duplicado($_POST['Nombre']);
//$name = $this->model->resultado2['Nombre'];
if(!empty($name)){
die("No se puede crear una solucion con el mismo nombre");
}else{
$solucion = new solucion();
$solucion->id = $_REQUEST['id'];
$solucion->Nombre = $_REQUEST['Nombre'];
$solucion->Tipo = $_REQUEST['Tipo'];
$solucion->Descripcion = $_REQUEST['Descripcion'];
$solucion->Pagina = $_FILES['Pagina']['name'];
}
header("Location: index.php");
}
I have a problem with my form, when I get in my website with Xampp, the webpage is not completed, doesn't appear the "region" combo box, the "fono" text field and the buttons, I don't know why it happens :( I wonder if someone could help me with this issue, please, as I fixed the bracket problems, now this problem is really freaking me out indeed.
<!DOCTYPE html>
<html>
<head>
<title>Formulario de datos</title>
<meta charset="UTF-8">
<script src="js/jquery.js"></script>
<script src="js/NumeroLetra.js"></script>
<script src="js/Hora.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery.Rut.js"></script>
<script src="js/jquery.validate.js"></script>
</head>
<body onLoad="IniciarReloj24()">
<?php
ini_set('error_reporting',0);
include ('funciones.php');
?>
<form action = " " method="post">
<?php
//comprobamos el evento del boton
if ($_POST['btnRutBuscar'] == "Buscar"){
$cnn = Conectar();
//concatenamos los inputs para realizar el formato del rut
$rutt = $_POST['txtRut']."-".$_POST['txtDigito'];
//sentencia sql anidada entre registro y regiones
$sql = "select re.rut, re.nombres, re.apellidos, re.fnac, re.sexo, r.id, r.region, re.fono from registro re, regiones r where (re.region = r.id) and (re.rut = '$rutt')";
$rs = mysqli_query($cnn, $sql);
while ($row = mysqli_fetch_array($rs)){
$rut = $row['rut'];
$nom = $row['nombres'];
$ape = $row['apellidos'];
$fna = $row['fnac'];
$sex = $row['sexo'];
//recogemos el id de la tabla regiones que sera utilizada en el combo box de regiones
$id = $row['id'];
$reg = $row['region'];
$fon = $row['fono'];
//se les añade los value a los inputs para poder recibir los valores de la base de datos
}
}
?>
<center><h1>Formulario de datos: todo en uno</h1></center>
<center><h2>Creado por Matías Cáceres y Francisco Tello</h2></center>
<br>
<br>
<div align="center"><label>Rut:</label>
<input type="text" name="txtRut" id="txtRut" onkeypress="ValidaSoloNumeros()" value="<?php echo $rut?>" /> -
<input type="text" name="txtDigito" id="Verificador" size="2" onkeypress="ValidaSoloNumeros()" />
<input type="submit" name="btnRutBuscar" id="btnBuscar" value="Buscar" /></div>
<br>
<br>
<div align="center"><label>Nombres:</label>
<input type="text" name="txtNombres" id="txtNombres" onkeypress="txNombres()" value="<?php echo $nom ?>" />
<br>
<br>
<div align="center"> <label>Apellidos:</label>
<input type="text" name="txtApellidos" id="txtApellidos" onkeypress="txNombres()" value="<?php echo $ape ?>"/>
<br>
<br>
<div align="center"><label>Fecha de Naciemiento:</label>
<input type="date" name="txtFecha" value="<?php echo $fnac ?>" />
<br>
<br>
<div align="center"><label>Sexo:</label>
<select name="txtSexo">
<option value=""><?php $sex ?></option>
<option value = "Masculino">Masculino</option>
<option value = "Femenino">Femenino</option>
</select></div>
<br>
<br>
<div align="center"><label>Región:</label>
<?php
$cnn=Conectar();
$sql="select region from regiones";
$rs = mysqli_query($cnn,$sql); ?>
<select name="txtRegion">
<option value=""><?php echo $reg ?></option>
<?php while ($row=mysqli_fetch_array($rs))
{echo '<option>'.$row["region"];}
?>
</select>
</div>
<br>
<br>
<div align="center"><label>Fono:</label>
<input type="text" name="txtFono" id="txtFono" onkeypress="ValidaSoloNumeros()" value="<?php echo $fon ?>" />
</div>
<br>
<br>
<table>
<td><input type="submit" name="btnAgregar" id="btnAgregar" value="Agregar"/></div></td>
<td><input type="submit" name="btnModificar" id="btnModificar" value="Modificar"/></div></td>
<td><input type="submit" name="btnEliminar" id="btnEliminar" value="Eliminar"/></div></td>
<td><input type="submit" name="btnVerTodos" id="btnVerTodos" value="Ver Todos"/></div></td>
</table>
<?php
if($_POST['btnAgregar']=="Agregar")
{
$cnn = Conectar();
$rutt = $_POST['txtRut']."-".$_POST['txtDigito'];
$nom = $_POST['txtNombres'];
$ape = $_POST['txtApellidos'];
$fna = $_POST['txtFecha'];
$sexo = $_POST['txtSexo'];
$reg = $_POST['txtRegion'];
$fon = $_POST['txtFono'];
$sql = "insert into registro values('$rutt','$nom','$ape','$fna','$sexo','$reg','$fon')";
//este if lo acabo de colocar, es mas que nada para saber si ocurrio algo malo al momento de ejecutar la funcion (***** El if es necesario en todos los botones*****)
#Comprobar el nombre de las variables
if (empty($rut) || empty($nom) || empty($ape) || empty($fnac) || empty($sex) || empty($reg) || empty($fon)) {
echo "<script>alert('Todos los campos son obligatorios');</script>";
if( mysqli_query($cnn,$sql)){
echo "<script>alert('Se han grabado los datos')</script>";
echo "<script>window.location='index.php'</script>";
}else{
echo "<script>alert('ocurrio un problema');</script>";
}
}
}
if($_POST['btnEliminar']=="Eliminar")
{
$cnn = Conectar();
$rut = $_POST['txtRut']."-".$_POST['txtDigito'];//es necesario concadenar los dos inputs para que funcione la consulta
$sql = "delete from registro where (rut = '$rut')";
mysqli_query($cnn,$sql);
echo "<script>alert('Se eliminó el registro')</script>";
}
if($_POST['btnModificar']=="Modificar")
{
$cnn = Conectar();
$rutt = $_POST['txtRut']."-".$_POST['txtDigito']; //es necesario concadenar los dos inputs para que funcione la consulta
$nom = $_POST['txtNombres'];
$ape = $_POST['txtApellidos'];
$fna = $_POST['txtFecha'];
$sex = $_POST['txtSexo'];
$reg = $_POST['txtRegion'];
$fon = $_POST['txtFecha'];
$sql = "update registro set nombres='$nom', apellidos='$ape', fnac='$fna', sexo='$sex', region='$reg', fono='$fon' where rut='$rutt'";
mysqli_query($cnn,$sql);
echo "<script>alert('Se han editado los datos')</script>";
}
?>
</form>
<table border = '1'>
<tr>
<?php date_default_timezone_set('America/Santiago');
$vaFecha = date('d-m-y');
?>
<td>Fecha</td>
<td><input type = "text" name="caja_fecha" value = "<?php echo $vaFecha; ?>" disabled="disabled"></td>
</tr>
</table>
<form name="reloj24">
<input type="text" size="8" name="digitos" value=" " disabled="disabled">
</form>
<script>
$('#txtRut').Rut( {
digito_verificador: '#Verificador',
on_error: function(){ alert('Rut incorrecto');
$("#txtRut").val("");
$("#Verificador").val("");
}
} );
</script>
</body>
</html>
enter image description here
I'm trying to make a simple form that sends the user input to my email. I don't know PHP so I'm having some trouble here. I can't make the form include the checkboxes' results in the mail. I tried several times but I can't make it work. It's in spanish, sorry for that!
Here is the code:
contactoformescritorio.php:
<?php
$where_form_is = "contacto.html".$_SERVER['SERVER_NAME'].strrev(strstr(strrev($_SERVER['PHP_SELF']),"/"));
mail("MY#MAIL.com","Formulario de pedido de copias","Form data:
Nombre: " . $_POST['cd-name'] . "
Email: " . $_POST['cd-email'] . "
Tamanio: " . $_POST['tamanio'] . "
Acabado: " . $_POST['acabado'] . "
Incluir en la cotizacion: " .implode(',',$_POST['agregados'])."\n" . "
Foto elegida e información adicional: " . $_POST['cd-textarea'] . "
.
");
include("confirm.html");
/*
* Procesar el formulario unicamente si el usuario lo envió. En cambio,
* si se accede directamente a esta página, redirigir al formulario.
*/
if ($_SERVER['REQUEST_METHOD'] == "POST") {
function check_input_value($input_value) {
// Remove extra spaces of strings (beginning and end)
$input_value = trim($input_value);
// Prevent XSS
$input_value = htmlspecialchars($input_value);
return $input_value;
}
// Obtenemos los valores que el usuario ingresó
$tamanio = $_POST['tamanio'];
$acabado = $_POST['acabado'];
$tamanio = check_input_value($tamanio);
$acabado = check_input_value($acabado);
if (empty($tamanio) || (empty($acabado)) || (empty($agregados))) {
echo "Error: sin completar";
exit;
}
echo $tamanio . "<br />";
echo $acabado . "<br />";
// Muestra los checkbox seleccionados por el usuario
if (!empty($_POST['agregados'])) {
foreach ($_POST['agregados'] as $agregados) {
echo $agregados . "<br />";
}
}
} else {
header("Location: formulario.php");
}
?>
A friend helped me with the form so it may be a little messy as I copied and pasted some parts.
contacto.html
<form class="cd-form floating-labels" name="htmlform" method="post" action="contactoformescritorio.php">
<fieldset>
<legend>Información personal</legend>
<div class="error-message">
<p>Por favor ingresa un email valido</p>
</div>
<div class="icon">
<label class="cd-label" name="cd-name" for="cd-name">Nombre</label>
<input class="user" type="text" name="cd-name" id="cd-name" required>
</div>
<div class="icon">
<label class="cd-label" name="cd-email" for="cd-email">Email</label>
<input class="email error" type="email" name="cd-email" id="cd-email" required>
</div>
</fieldset>
<fieldset>
<legend>Informacion de la impresion</legend>
<div>
<h4>Tamaño</h4>
<p class="cd-select icon">
<select class="size" name="tamanio" id="cd-size">
<option value="0">Seleccionar Tamaño</option>
<option value="1">Impresion 20x30</option>
<option value="2">Iman de 6 fotos 5x5</option>
<option value="3">Tamaño 3</option>
</select>
</p>
</div>
<div>
<h4>Acabado</h4>
<ul class="cd-form-list">
<li>
<input type="radio" name="acabado" value="mate" id="mate" checked="checked"/><label for="mate">Mate</label>
</li>
<li>
<input type="radio" name="acabado" value="brillo" id="brillo"/><label for="brillo">Brillo</label>
</li>
</ul>
</div>
<div>
<h4>Agregar a la cotización</h4>
<ul class="cd-form-list">
<li><input type="checkbox" name="agregados[]" value="marco" id="marco"><label for="marco">Marco</label></li>
<li><input type="checkbox" name="agregados[]" value="envio" id="envio"><label for="envio">Envio (indicar direccion)</label></li>
</ul>
</div>
<div class="icon">
<label class="cd-label" for="cd-textarea">Foto elegida e información adicional</label>
<textarea class="message" name="cd-textarea" id="cd-textarea" required></textarea>
</div>
<div>
<input type="submit" value="Enviar mensaje">
</div>
</fieldset>
</form>
Your checkboxes are both of the name agregados[], which makes them an array. You currently handle them via implode, then later with a foreach.
Before your mail, run a foreach like this
if (!empty($_POST['agregados'])) {
foreach ($_POST['agregados'] as $key=>$value) {
if ($key > 0) {
$agregados .= ", $value";
} else {
$agregados .= "$value";
}
}
} else {
$agregados .= "(nothing selected)";
}
This will set the variable $agregados with the values that was selected from the checkboxes, and if nothing is selected, display such a message instead.
Then, in your mail, replace the line that handles the checkboxes with the variables.
Replace:
Incluir en la cotizacion: " .implode(',',$_POST['agregados'])."\n" . "
with
$agregados
Also, please know that your mail will be sent regardless when you enter contactoformescritorio.php, as there is no checking if a form has been sent to it. The check you are performing (if ($_SERVER['REQUEST_METHOD'] == "POST")) comes after that.
As a final note, not one that's related to your question directly, your select has no require-attribute, so your PHP script exits if nothing is selected (where you are checking of one of the three statements are empty). Just put a required attribute in your select, such as this
<select class="size" name="tamanio" id="cd-size" required>
Then your Seleccionar Tamaño can be set to a line like this
<option value="" selected style="display:none;">Seleccionar Tamaño</option>
This will make your form more "user-friendly", and not make the user fill in the form all over again if they forget to select something from the dropdown. Just a tip, nothing you really have to do.
I'm trying to check that the fields in the form below have been filled before it can be inserted into a database e.g. display a pop up with the fields that have not been filled in. It is just a simple Registration form.
<form name="form1" method="post" action="signup_ac.php">
<strong>Sign up</strong>
Username:<input name="username" type="text" id="username" size="30">
Password:<input name="password" type="password" id="password" size="15">
Name:<input name="name" type="text" id="name" size="30">
<select name="Month">
<option selected>Month</option>
<option value="January">January</option>
<option value="Febuary">Febuary</option
</select>
<select name=Year>
<option selected>Year</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
</select>
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Reset" value="Reset">
</form>
How do I do this using JavaScript or jQuery.
First of all, download the jQuery validate plugin and add it to your page. Then give each input you want to make a required field a class of required. Then in jQuery:
$(function() {
$("form").validate();
});
The validate plugin is very feature rich, so you can have different types of message displayed, different validation checks etc should you require. There's more information on that in the documentation.
Finally, as with all javascript front-end validation, make sure you validate user input on the server side too, just in case a user has javascript turned off in their browser.
A simple solution (using jQuery) would be:
$(document).ready(function () {
$('input').each(function () {
var $this = $(this);
var err = $this.attr('id') + ' is required.';
var errElem = $('<span />').text(err).css({'color': 'red', 'font-weight': 'bold'});
if ($this.val().length === 0) {
$this.parent('td').append(errElem);
}
});
});
Make sure to do server-side validation as well. There are some users who disable JavaScript (and then this wouldn't run).
Below is what I will have a normal html file
<html>
<head>
<script language="javascript">
function validateMe() {
if (firstname is blank) {
alert("Enter first name");
form.first.focus();
return false;
}
if (lastname is blank) {
alert("Enter last name");
form.last.focus();
return false;
}
return true;
}
</script>
<body>
// Form here
<input type="submit" name="submit" value="Submit" onClick="return validateMe()">
</body>
</html>
if first name is blank, form never submit the form...
Another way:
if($_SERVER['REQUEST_METHOD']=='POST'){
require('inc/mysqli_connect.php');
$errors=array();
/*Verifica el nombre*/
if(empty($_POST['first_name'])){
$errors[]='Verifique el campo de Nombre del participante';
}else{
$fina=mysqli_real_escape_string($dbc, trim($_POST['first_name']));
}
/*Verifica el apellido paterno*/
if(empty($_POST['ape_pat'])){
$errors[]='Verifique el campo de Apellido Paterno del participante';
}else{
$appa=mysqli_real_escape_string($dbc, trim($_POST['ape_pat']));
}
/*Verifica el apellido materno*/
if(empty($_POST['ape_mat'])){
$errors[]='Verifique el campo de Apellido Materno del participante';
}else{
$apma=mysqli_real_escape_string($dbc, trim($_POST['ape_mat']));
}
/*Verifica el genero*/
if(empty($_POST['gender'])){
$errors[]='Seleccione el Género del participante';
}else{
$gend=mysqli_real_escape_string($dbc, trim($_POST['gender']));
}
/*Verifica el correo electronico*/
if(empty($_POST['email'])){
$errors[]='Verifique el campo de Correo Electrónico del participante';
}else{
$coel=mysqli_real_escape_string($dbc, trim($_POST['email']));
}
/*and repeat the code above for all the input that you have in your form */
if(empty($errors)){
$q="INSERT INTO participante(nombre, paterno, materno, genero, correo, fechadenac, procedencia, ocupacion, asistencia, fechareg) VALUES ('$fina','$appa','$apma','$gend','$coel','$dabi','$prov','$ocup','$assi',NOW())";
$r=mysqli_query($dbc,$q);
if($r){
echo '
<p>
Nombre: <b>'.$_POST['first_name'].'</b><br />
Apellido Paterno: <b>'.$_POST['ape_pat'].'</b><br />
Apellido Materno: <b>'.$_POST['ape_mat'].'</b><br />
Genero: <b>'.$_POST['gender'].'</b><br />
Correo Electrónico: <b>'.$_POST['email'].'</b><br />
Fecha de nacimiento: <b>'.$_POST['date'].'</b><br />
Procedencia: <b>'.$_POST['provenance'].'</b><br />
Ocupación: <b>'.$_POST['ocuppation'].'</b><br />
¿Asistió? <b>'.$_POST['assistance'].'</b><br />
</p>
';
}else{
echo '
<h2><a>¡Error del Sistema!</a></h2>
<p>
El registro no pudo realizarse debido a un error del sistema. Disculpe los incovenientes.<br />
</p>
<p>
Error: '.mysqli_error($dbc).'<br />
Query: '.$q.'<br />
</p>
';
}
mysqli_close($dbc);
include ('inc/footer.html');
exit();
}else{
echo '
<p>
Revise que todo los campos hayan sido llenados correctamente.<br />
Se encontraron los siguientes errores: <br />
';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
echo '
</p>
<p>
Ingrese los datos faltantes e intente de nuevo.
</p>
';
}
mysqli_close($dbc);
}