I'm with a doubt,
I'm trying sending data to my database but it doesn't insert it them. How can i put them to send it?
index.php (script part):
<div id="wel">
<p id="title-call">Junta-te <font color="gray">a nós!</font></p><hr color="#c96308" noshadow />
<p id="subx">Percorre este mundo e torna-te o treinador número <font color="#c96308">UM</font>!</p>
</div>
<div id="loading"><br /></div>
<div id="warn2"><br /></div>
<div id="success"><br /></div>
<div id="subscribe">
<form id="sub" action="" method="POST" >
<input type="text" name="username" id="username" placeholder="Escreve aqui o teu Nome..." /><br />
<br />
<input type="text" name="email" id="email" placeholder="Escreve aqui o teu E-mail..." /><br /><br />
<input type="submit" id="submit" value="Subscrever" />
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#sub").submit(function() {
if($("#username").val()==""||$("#email").val()=="") {
$("#warn2").hide(36000);
$("#loading").css("display:inline");
$("#loading").html("<img src='images/ajax-loader.gif' width='1%' height='3%' /> A carregar...");
$("#loading").fadeIn(200);
$("#loading").fadeOut(200);
$("#warn2").css("display:none");
$("#warn2").html("Por favor escreve o teu nome e/ou email!<br />");
$("#warn2").hide(36000);
$("#warn2").fadeIn(1000);
$("#warn2").css("display:inline");
$("#warn2").fadeOut(7000);
}
else {
var s = $("#sub").serializeArray();
$.ajax({
url: "subscribe.php",
method: "POST",
data: s,
success: function() {
$("#success").css("display:none");
$("#success").hide(36000);
$("#loading").css("display:inline");
$("#loading").html("<img src='images/ajax-loader.gif' width='1%' height='3%' /> A carregar...");
$("#loading").fadeIn(200);
$("#loading").fadeOut(200);
$("#success").css("display:none");
$("#success").html("A tua subscrição foi efectuada com successo!");
$("#success").hide(36000);
$("#success").fadeIn(1000);
$("#success").css("display:inline");
$("#success").fadeOut(7000);
}
});
}
return false;
});
$("#MGa").click(function() {
$("#hidGames").css("display: inline");
$("#hidGames").fadeToggle(1000);
return false;
});
$("#MGa").mouseover(function() {
$("#arrow").html('<img src="images/arrow_wbm_hover.png" width="1%" height="1%" />');
});
$("#MGa").mouseout(function() {
$("#arrow").html('<img src="images/arrow.png" width="1%" height="1%" />');
});
$("#arrow").html('<img src="images/arrow.png" width="1%" height="1%" />');
});
</script>
subscribe.php :
<?php
include_once('db.php');
$username = $_POST["username"];
$email = $_POST["email"];
$date = date("Y-m-d h:i:s:A");
$sql = mysql_query("INSERT INTO subscribers VALUES('','$username','$email','$date')");
// mail function //
$to = $email;
$header = "From: info#wbm.pt";
$header. = "Content-Type: text/html;";
$subject = "Bem-vindo ao WBM!";
$body = "
Bem vindo ao WBM (World Basket Manager) <b>$username</b>,<br />
<br />
Sê o treinador número <i>UM</i> deste mundo de treinadores.<br />
- Cria a tua equipa;<br />
- Compra e Vende jogadores;<br />
- Calendário real;<br />
- Equipas Originais (NBA);<br />
- Estádios;<br />
- Forma as tuas próprias táticas;<br />
<br>
Tudo isto no mundo de treinadores de basquetbol!<br />
Lançamento da versão BETA:<br />
<b>Data prevísivel: <i>25 de Maio de 2014</i></b><br />
<br />
Muito Obrigado,<br />
<b>Equipa WBM</b>
<br />
<br />
<h6>Não responder a este e-mail!</h6>
";
// mail //
mail($to,$header,$subject,$body);
$rw = mysql_query("SELECT * FROM subscribers");
$rows = mysql_num_rows($rw);
if($rows!=0) {
$nrow = $rows;
}
else {
}
$to1 = "cell phone number";
$header1 = "From: 15030#wbm.pt";
$header1. = "Content-Type: text/play;";
$subject1 = "Bem-vindo ao WBM!";
$body1 = "
Têm $nrow que se subscreveram.
Muito Obrigado.
(Não responder a esta mensagem)
";
//sms to my cell phone //
mail($to1,$header1,$header1.,$subject1,$body1);
?>
db.php:
<?php
$connect = mysql_connect('localhost','root','');
mysql_select_db('subscribers');
?>
What can I do to this thing work guys?
You need to be checking for mysql errors, that would give you a big clue.
$query = "INSERT INTO subscribers VALUES('','$username','$email','$date')";
$sql = mysql_query($query) or throw new Exception("Query Failed: {$query}. Error: ".mysql_error());
Your code is open to SQL Injection, you should really be using MySQLi or PDO at this point, and if you're going to stick with mysql, escape your data.
Related
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 here trying to learn some php but i'm having some problems with my code now i'm trying to solve the "getimagesize(): Filename cannot be empty" but there are many others like:/
-Undefined variable: date/
-Undefined variable: imgData /
And yes i've tried other codes and still have the same problem/
So here's my code.
<?php
$link = mysqli_connect("blah", "blah", "blah", "blah");
if($link === false){
die("ERRRO: Não foi possivel a conexão com a base de dados. " . mysqli_connect_error());
}
if(!empty($_FILES['userImage']['tmp_name'])
&& file_exists($_FILES['userImage']['tmp_name'])) {
$imgData= addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
}
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$portal = mysqli_real_escape_string($link, $_POST['field1']);
$datacri = mysqli_real_escape_string($link, $_POST['field2']);
$datacri = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
$datapub = mysqli_real_escape_string($link, $_POST['field3']);
$datapub = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
$titulo = mysqli_real_escape_string($link, $_POST['field4']);
$keyword = mysqli_real_escape_string($link, $_POST['field5']);
$hashtags = mysqli_real_escape_string($link, $_POST['field6']);
$pedido = mysqli_real_escape_string($link, $_POST['field7']);
$autor = mysqli_real_escape_string($link, $_POST['field8']);
if (!$portal) {
echo '<script type="text/javascript"> alert("Preencha todos os campos "); </script>';
mysqli_close($link);
}
$sql = "INSERT INTO pedidos (p_portal, p_datacri, p_datapub, p_titulo, p_titulo, p_keywords, p_hashtags, p_imageType, p_imageData, p_pedido, p_autor)
VALUES('$portal', '$datacri', '$datapub', '$titulo', '$keyword', '$hashtags', '{$imageProperties['mime']}', '{$imgData}', '$pedido', '$autor')";
if(mysqli_query($link, $sql)){
echo '<script type="text/javascript"> alert("Portal Criado"); </script>';
} else{
echo "ERRO: Não foi possivel executar o comando $sql. " . mysqli_error($link);
}
?>
And my html file:
<form action="php\pedidos\p_ins.php" enctype="multipart/form-data" method="post">
<link rel="stylesheet" href="css\pedidos.css">
<fieldset>
<legend><span class="number">1</span> Criar Pedido</legend>
<label for="portal">Portal</label
<?php
$link = mysqli_connect("blah", "blah", "blah", "blah");
if($link === false){
die("ERRRO: Não foi possivel a conexão com a base de dados. " . mysqli_connect_error());}
$result = $link->query("select po_id, po_nome from portais");
echo "<html>";
echo "<body>";
echo "<select name='field1' name='po_id'>";
echo "<option value=''>----Selecione um Portal----</option>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['po_id'];
$name = $row['po_nome'];
echo '<option value="'.$id.'">'.$name.'</option>';
} echo "</select>";
echo "</body>";
echo "</html>";?>
<label>Data de Criação</label>
<input type="date" name="field2" placeholder="Data de publicacao do Post">
<label>Data de Publicação</label>
<input type="date" name="field3" placeholder="Data de publicacao do Post">
<label>Titulo</label>
<input type="text" name="field4" placeholder="Insira aqui o Titulo">
<label>Keywords</label>
<input type="text" name="field5" placeholder="Insira aqui as Keywords">
<label>Hashtags</label>
<input type="text" name="field6" placeholder="Insira aqui as Hashtags">
<label>Imagem</label>
<p> </p>
<input type="file" name="userImage" accept="image/*" class="inputFile"> <p> </p>
<label>Pedido</label>
<textarea type="text" name="field7" placeholder="Insira aqui o Pedido"></textarea>
<label for="autores">Autor</label>
<?php
$result = $link->query("SELECT *FROM autores");
echo "<html>";
echo "<body>";
echo "<select name='field8' name='a_id'>";
echo "<option value=''>----Selecione um autor----</option>";
while ($row = $result->fetch_assoc()) {
unset($id, $name)
; $id = $row['a_id'];
$name = $row['a_nome'];
echo '<option value="'.$id.'">'.$name.'</option>';
} echo "</select>";
echo "</body>";
echo "</html>";?>
<input type="submit" value="Enviar" />
<div id='footer'>
</div>
</form>
Thanks.
Make sure your input type="file" is inside a form that has an enctype="multipart/form-data" or it will not send to file to your PHP script and $_FILES['userImage']['tmp_name'] will be empty
<form method="post" enctype="multipart/form-data" action="yourphpfile.php">
<label>Data de Criação</label>
<input type="date" name="field2" placeholder="Data de publicacao do Post">
<label>Data de Publicação</label>
<input type="date" name="field3" placeholder="Data de publicacao do Post">
<label>Titulo</label>
<input type="text" name="field4" placeholder="Insira aqui o Titulo">
<label>Keywords</label>
<input type="text" name="field5" placeholder="Insira aqui as Keywords">
<label>Hashtags</label>
<input type="text" name="field6" placeholder="Insira aqui as Hashtags">
<label>Imagem</label>
<p> </p>
<input type="file" name="userImage" class="inputFile"> <p> </p>
<label>Pedido</label>
<textarea type="text" name="field7" placeholder="Insira aqui o Pedido"></textarea>
<label for="autores">Autor</label>
</form>
As for your PHP code, I would advise putting all the block concerning the insert to database inside your if block. Plus you have some errors that are fixed here :
if(!empty($_FILES['userImage']['tmp_name'])
&& file_exists($_FILES['userImage']['tmp_name'])) {
$imgData= mysqli_real_escape_string($link, file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$portal = mysqli_real_escape_string($link, $_POST['field1']);
$date = mysqli_real_escape_string($link, $_POST['field2']);
$datacri = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
$date = mysqli_real_escape_string($link, $_POST['field3']);
$datapub = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
$titulo = mysqli_real_escape_string($link, $_POST['field4']);
$keyword = mysqli_real_escape_string($link, $_POST['field5']);
$hashtags = mysqli_real_escape_string($link, $_POST['field6']);
$pedido = mysqli_real_escape_string($link, $_POST['field7']);
$autor = mysqli_real_escape_string($link, $_POST['field8']);
if (!$portal) {
echo '<script type="text/javascript"> alert("Preencha todos os campos "); </script>';
mysqli_close($link);
}
$sql = "INSERT INTO pedidos (p_portal, p_datacri, p_datapub, p_titulo, p_keywords, p_hashtags, p_imageType, p_imageData, p_pedido, p_autor)
VALUES('$portal', '$datacri', '$datapub', '$titulo', '$keyword', '$hashtags', '{$imageProperties['mime']}', '{$imgData}', '$pedido', '$autor')";
if(mysqli_query($link, $sql)) {
echo '<script type="text/javascript"> alert("Portal Criado"); </script>';
} else{
echo "ERRO: Não foi possivel executar o comando $sql. " . mysqli_error($link);
}
} else {
echo "ERROR: couldn't get image Data";
}
?>
......
bringing trouble again, I have a PHP form with which I receive information (name and email) and send the information by email and in turn allows downloading a file with JS validation, if I remove sending email, save the information in MySQL but if I put sending mail, do not save the info ...
Here´s the code from index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Muestra Gratuita</title>
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="shortcut icon" href="img/favicon.ico">
<div id="fb-root"></div>
<script type="text/javascript">
function validar(){
var copia = document.getElementById("txtcopia").value;
var captcha = document.getElementById("captcha").value;
if (copia == captcha) {
window.open("muestra/Corazon_prodigo.pdf", "_blank");
}else{
alert("El codigo ingresado no coincide");
}
}
</script>
<script type="text/javascript">
document.oncontextmenu = function(){return false;}
</script>
</head>
<body>
<div class="container" style="padding-top : 50px;">
<div class="row">
<div class="col-md-6">
<div class="display-block">
<img class="img-responsive center-block" src="img/muestra.jpg">
</div>
</div>
<div class="col-md-6">
<p class="lead">
Por favor completa el formulario para que puedas descargar
<strong>GRATIS</strong>
una muestra (Primeras páginas) del libro Corazón Pródigo:
<br>
</p>
<div class="alert" style="display: none" role="alert"></div>
<form class="email-form" method="POST" action="send.php">
<div class="form-group">
<label for="name">Nombre Completo</label>
<input class="form-control" name="name" type="text" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control" name="email" type="email" required>
</div>
<br>
<label class="lead" for="txtcopia">Introduce el texto del campo de abajo</label>
<input class="form-control" type="text" name="txtcopia" id="txtcopia" size="10">
<br>
<br>
<input class="captcha" type="text" name="captcha" id="captcha" value=<?php echo captcha(); ?> size="8" readonly>
<br>
<br>
<br>
<button id="buscarbtn" class="btn btn-success" type="submit" value="registrar" name ="buscarbtn" onclick="validar();">Suscribirse</button>
<br>
<br>
<a class="download_button btn btn-lg btn-success center-block" style="display:none" download="" href="muestra/Corazon_prodigo.pdf">Descarga Ahora</a>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
#error_reporting(0);
$sqlhost = 'localhost';
$sqluser = 'root';
$sqlpass = '';
$sqldb = 'registro';
$sqltable= 'registro';
function captcha() {
$k="";
$param="1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$max=strlen($param)-1;
for ($i=0; $i<6; $i++) {
$k.=$param{mt_rand(0,$max)};
}
return $k;
}
$db = mysqli_connect($sqlhost, $sqluser, $sqlpass, $sqldb); //Nuestra variable para establecer la conexión a la base de datos
if(!$db){die("Error al conectar con la db" . mysql_error());}
$name = isset($_POST['name']) ? $_POST['name'] : NULL; // Tomamos el texto del input "nombre"
$email = isset($_POST['email']) ? $_POST['email'] : NULL; // Tomamos el texto del input "apellido"
$date = date('Y-m-d');
// Insertaremos la información a la tabla Nombre y Apellido, donde VALUES declara el texto que ingresaremos
$query = "INSERT INTO ".$sqltable."(name, email, date) VALUES('".$name."', '".$email."', '".$date."');";
mysqli_select_db($db,$sqldb); //verificaremos la conexión a nuestra base de datos
$insert_value = mysqli_query($db, $query); // Declaramos la variable $insert_value para usarla cómo un bool, en caso de que esta consulta falle
if(!$insert_value) //Crearemos la consulta
die('Error: ' . mysqli_error($db)); // Si falla, nos mostrará este texto, seguido del error.
mysqli_close($db); // Detenemos la conexión de la base de datos
?>
Here´s the code from send.php:
<?php
$para = "example#example.com";
require 'PHPMailerAutoload.php';
$mail=new phpmailer();
$mail->PluginDir = "includes/";
$mail->Mailer = "smtp";
$mail->Host = "mail.example.com";
$mail->SMTPAuth = true;
$mail->Username = "contact#example.com";
$mail->Password = "H1hs4h45";
$mail->From = "contact#example.com";
$mail->FromName = "contacto WEB";
$mail->Timeout=30;
$mail->AddAddress($para);
$mail->Subject = "NUEVO USUARIO REGISTRADO";
$mail->Body = $_POST['name'].chr(13).chr(10).$_POST['email'];
$mail->IsHTML(true);
if($mail->Send())
{
echo'<script type="text/javascript">
alert("Enviado Correctamente");
window.location="http://example.com/index.php"
</script>';
}
else{
echo'<script type="text/javascript">
alert("NO ENVIADO, intentar de nuevo");
window.location="http://example.com/index.php"
</script>';
}
?>
So the question is, how can I run the email sending and turn to save the information in MySQL at the same time?
Because, if I put send.php content in the same file index.php or vice versa, when the page loads it generates a loop and sends email every 30 seconds, and I forgot to say, when the email are sent, it generates a MySQL row but it is empty...
I'm trying to send email with PHP using an Ajax request, but my "echo" on the PHP file just seems to not work and I have no idea why.
Thinking that my PHP code was wrong, I replaced my code with just an "echo" as posted below, but it still is not working.
I'm posting my HTML, JS, PHP and also the firebug response, which I don't quite understand.
HTML
<form id="contactForm" class="contact-form">
<div class="form-group form-icon-group">
<input class="form-control" id="name" name="name" placeholder="Nome" type="text" required title="Por favor, preencha esse campo." x-moz-errormessage="Por favor, preencha esse campo."/>
<i class="fa fa-user"></i>
</div>
<div class="form-group form-icon-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required title="Por favor, preencha esse campo corretamente." x-moz-errormessage="Por favor, preencha esse campo corretamente.">
<i class="fa fa-envelope"></i>
</div>
<div class="form-group form-icon-group">
<textarea class="form-control" id="message" name="message" placeholder="Qual sua mensagem?" rows="10" required title="Por favor, preencha esse campo." x-moz-errormessage="Por favor, preencha esse campo."> </textarea>
<i class="fa fa-pencil"></i>
</div>
<div>
<a id="btnEnviar" value="Enviar Email" class="btn btn-primary btn-lg">Enviar Email</a>
</div>
<div>
<label id="labelResposta" style="font-size: 22px; margin-top: 20px; display: none;">Email enviado com sucesso!</label>
</div>
<div id="messages"></div>
</form>
JS
$('#btnEnviar').click(function() {
$('#btnEnviar').html('Enviando...');
$('#btnEnviar').attr('disabled', 'disabled');
var formData = {
nome: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// console.log(formData);
// console.log($("#contactForm").serialize());
if(!formData.nome) {
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').html('Por favor preencha seu nome.');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
} else if(!formData.email) {
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').html('Por favor preencha seu email.');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
} else if(!formData.message) {
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').html('Por favor preencha sua mensagem.');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
} else {
$.ajax({
url: 'file:///home/phellipe/Desktop/projetos/phperin/email/email_processor.php',
type: "POST",
data: formData,
success: function(data) {
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').html('Email enviado com sucesso!');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
},
error: function(x, e){
console.log(x);
console.log(e);
if(x.status==0){
$('#labelResposta').html('Você não está online!\n Por favor, verifique sua conexão.');
}else if(x.status==404){
$('#labelResposta').html('URL não encontrada.');
}else if(x.status==500){
$('#labelResposta').html('Erro interno.');
}else if(e=='parsererror'){
$('#labelResposta').html('Erro de parse.');
}else if(e=='timeout'){
$('#labelResposta').html('Timeout.');
}else {
$('#labelResposta').html('Erro desconhecido.\n'+x.responseText);
}
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
}
});
}
return false;
});
PHP (test)
<?php echo "string"; ?>
PHP (real)
<?php
$sender_name = trim(ucfirst($_REQUEST['nome']));
$sender_email = trim($_REQUEST['email']);
$sender_message = trim(ucfirst($_REQUEST['message']));
$html_email = '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PhPerin</title>
</head>
<body>
<p>Olá</p>
<p>Notificamos que <em>' . $sender_name . '</em> entrou em contato</p>
<p>Deixou a seguinte mensagem:</p>
<p>' . $sender_message . '</p>
<p>Você pode entrar em contato pelo seguinte email ' . $sender_email . '</p>
</body>
</html>';
require_once("send_email.php");
echo "string";
?>
Firebug Response
readyState 4
responseText "<?php echo "string"; ?>"
status 200
statusText "parsererror"
I wonder if you need to escape those double quotes. Where it says
<meta charset="UTF-8">
try
<meta charset=\"UTF-8\">
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);
}