Today I'm facing another error related with AJAX.
I'm pretending to build a user registration system using ajax and php, with mvc architecture.
I built a login system without ajax and works without any problem, there is connectivity and interaction between all sides.
I'm almost sure that the error comes because of the JS file, I've passed my file through the JSHint to detect errors but nothing found, probably there is some mistake in the logic of the code.
First of all, before to post my code, I'll show you my data files structure to save you some headache thinking about the paths:
I'm going to paste the codes here and then I'll comment something about each piece of code.
View/register.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<link rel="stylesheet" href="../css/register.css">
<script src="../js/valReg.js"></script>
<section class="registerPage1">
<section class="registerPage2">
<form method="post" action="#" onsubmit="" id="regTopfit" name="regTopfit">
<ul>
<input type="button" value="Full Registration" id="advReg">
<li>Nombre:</li>
<li><input id="i_firstname" type="text" name="firstname" placeholder="Firstname"><input id="i_lastname" type="text" name="lastname" placeholder="Lastname"></li>
<br>
<li><input type="text" id="i_dni" placeholder="Your ID"></li>
<li><input id="i_username" type="text" name="username" placeholder="Username"><span id="user-result"></span></li>
<li><input id="i_email" type="email" name="email" placeholder="Email address"></li>
<span class="extraFieldsRegistration">
<li><input type="text" id="i_phone" placeholder="Phone number"></li>
<li><input type="text" id="i_address" placeholder="Address"></li>
<li><input type="text" id="i_city" placeholder="City"></li>
<li><input type="text" id="i_postal" placeholder="Postal Code"></li>
<li><input type="text" id="i_province" placeholder="Province"></li>
<li><input type="text" id="i_creditcard" placeholder="Credit Card number"></li>
</span>
<li><div id="regMailError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li>Crear contraseña:</li>
<li><input id="i_pass1" type="password" name="pass1" placeholder="6-20 caracteres" ></li>
error<li><div id="regPLenError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input id="i_pass2" type="password" name="pass2" placeholder="Repite la contraseña" ></li>
error<li><div id="regPMatchError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="checkbox" name="offers" value="Yes">Quiero recibir las últimas novedades de TopFIT</li>
<li><input id="i_conditions" type="checkbox" name="conditions" value="accepted" >He leído y acepto la política de privacidad.</li>
error<li><div id="regCondError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="button" id="register" value="Crea tu cuenta"></li>
<li><span id="result"></span></li>
</ul>
</form>
</section>
</section>
</body>
</html>
Nothing to say about the view.
Controller/register.php
<?php
//REGISTER controller
require "../model/backend.php";
$username = $_POST["#i_username"];
$email = $_POST["#i_email"];
$password = $_POST["#i_pass1"];
$firstname = $_POST["#i_firstname"];
$lastname = $_POST["#i_lastname"];
$dni = $_POST["#i_dni"];
$phone = $_POST["#i_phone"];
$address = $_POST["#i_address"];
$city = $_POST["#i_city"];
$postal = $_POST["#i_postal"];
$province = $_POST["#i_province"];
$creditcard = $_POST["#i_creditcard"];
$dbcom = new dbInteraction;
$dbcom->register($firstname, $lastname, $email, $dni, $phone, $address, $city, $postal, $province, $creditcard, $username, $password);
$dbcom->conclose();
?>
In that case, as you can see, I pick the values of my inputs and then I call my register function passing all the arguments to perform the registration. I think that everything is cool here too.
model/backend.php
<?php
//model!
class dbInteraction{
private $connection;
private $server = "127.0.0.1";
private $s_user = "root";
private $s_password ="";
private $db = "youtube";
private $dni;
private $firstname;
private $lastname;
private $username;
private $password;
private $phone;
private $address;
private $city;
private $postal;
private $province;
private $creditcard;
public function __construct(){
$this->connection = new mysqli($this->server, $this->s_user, $this->s_password, $this->db);
if($this->connection->connect_errno){
// echo $db->connect_error;
die('Sorry, we are having problems.');
}
}
public function conclose(){
$this->connection->close();
}
public function login($user, $password){
$this->user = $username;
$this->password = $password;
$query = "SELECT id, firstname, lastname, password FROM people WHERE username = '".$this->user."' AND password = '".$this->password."' ";
$myquery = $this->connection->query($query);
if ($row = mysqli_fetch_array($myquery)){// or die($this->connection->error)) {
session_start();
$_session['id'] = $row['id'];
$_session['firstname'] = $row['firstname'];
$_session['lastname'] = $row['lastname'];
echo 'Signed in.' , '<br>';
echo 'Welcome' , $_session['firstname'];
}else{
echo 'Check your data and try again.';
}
}
public function register($firstname, $lastname, $email, $dni, $phone, $address, $city, $postal, $province, $creditcard, $username, $password){
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->email = $email;
$this->dni = $dni;
$this->phone = $phone;
$this->address = $address;
$this->city = $city;
$this->postal = $postal;
$this->province = $province;
$this->creditcard = $creditcard;
$this->username = $username;
$this->password = $password;
$query = "INSERT INTO users (username, email, password, firstname, lastname, dni, phone, address, city, postal, province, creditcard) VALUES ('$username','$email','$password', '$firstname', '$lastname', '$dni', '$phone', '$address', '$city', '$postal', '$province', $creditcard)";
$myquery = $this->connection->query($query);
if ($row = mysqli_fetch_array($myquery)) {
session_start();
$_session['id'] = $row['id'];
$_session['firstname'] = $row['firstname'];
$_session['lastname'] = $row['lastname'];
echo 'You have been correctly registered. Welcome to TopFIT ', $_session['firstname'];
}else{
echo 'Something went wrong.';
}
}
public function newPassword($email){
$this->email = $email;
}
}
We have to focus in the register function, which is that simple as it looks. I think that I'm sure of the syntax that I used there.
JS File
$(document).ready(function(){
var showFull = $(".extraFieldsRegistration");
var fullReg = $("#advReg")
fullReg.click(function(){
showFull.css('display','inline');
});
$("#register").click(function(){
var mailValue = $("#i_email").val();
var usernameValue = $("#i_username").val();
var passwordValue = $("#i_pass1").val();
var passwordValue2 = $("#i_pass2").val();
var conditionsValue = $("#i_conditions").val();
var fnameValue = $("#i_firstname").val();
var lnameValue = $("#i_lastname").val();
var dniValue = $("#i_dni").val();
var phoneValue = $("#i_phone").val();
var addrValue = $("#i_address").val();
var cityValue = $("#i_city").val();
var postalValue = $("#i_postal").val();
var provValue = $("#i_province").val();
var ccValue = $("#i_creditcard").val();
var __mailError = document.getElementById('regMailError');
var __passLenError = document.getElementById('regPLenError');
var __passMatchError = document.getElementById('regMatchError');
var __condError = document.getElementById('regCondError');
if (mailValue === '' || passwordValue === '' || passwordValue2 === '' || usernameValue === ''){
alert('completa todos los campos');
}else{
if (passwordValue != passwordValue2){
alert('contraseñas distintas');
}else{
if (document.getElementById('conditions').checked){
$.ajax({
type: "POST",
url: "../controller/register.php",
data: {
username: usernameValue,
email: mailValue,
password: passwordValue,
firstname: fnameValue,
lastname: lnameValue,
dni: dniValue,
phone: phoneValue,
address: addrValue,
city: cityValue,
postal: postalValue,
province: provValue,
creditcard: ccValue
},
success: function(msg){
$("#result").html(msg);
},
error:function(){
alert('error');
}
});
}else{
alert('Debes aceptar las condiciones');
}
}
}
}); //click del register
}); //document ready
Ok, definitely I think that here there are mistakes.
In the beginning, there is a piece of code that pretends to modify the property of a view span, turning that property (display) from none to inline.
I previously used this code in other files and functions and it was working correctly, now I have no idea why it doesn't work.
Then there is the form validator and after that, if everything goes fine, inside an if, I try to perform the communication to the other mvc files passing the arguments that should be recorded to my db.
You'll notice that there are a lot of unused variables, I know, I'll use these ones to modify the css (in case of error) of some divs that I have in the view, but I decided to use alerts to debug. So where you see alert, there will be a css modifier.
I think that everything has logic but despite of my things, it doesn't work.
I've been looking for solutions and I saw that using JSON, probably I'll save time, code and problems but I have to do this without json, at least for now.
Did you find some error? Do you have a better idea to build this system?
As always, I'll appreciate your help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- ADD / LOAD JQUERY HERE with the correct path -->
<script src="../js/jquery.js"></script>
</head>
<body>
<link rel="stylesheet" href="../css/register.css">
<script src="../js/valReg.js"></script>
<section class="registerPage1">
<section class="registerPage2">
<form method="post" action="#" onsubmit="" id="regTopfit" name="regTopfit">
<ul>
<input type="button" value="Full Registration" id="advReg">
<li>Nombre:</li>
<li><input id="i_firstname" type="text" name="firstname" placeholder="Firstname"><input id="i_lastname" type="text" name="lastname" placeholder="Lastname"></li>
<br>
<li><input type="text" id="i_dni" placeholder="Your ID"></li>
<li><input id="i_username" type="text" name="username" placeholder="Username"><span id="user-result"></span></li>
<li><input id="i_email" type="email" name="email" placeholder="Email address"></li>
<span class="extraFieldsRegistration">
<li><input type="text" id="i_phone" placeholder="Phone number"></li>
<li><input type="text" id="i_address" placeholder="Address"></li>
<li><input type="text" id="i_city" placeholder="City"></li>
<li><input type="text" id="i_postal" placeholder="Postal Code"></li>
<li><input type="text" id="i_province" placeholder="Province"></li>
<li><input type="text" id="i_creditcard" placeholder="Credit Card number"></li>
</span>
<li><div id="regMailError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li>Crear contraseña:</li>
<li><input id="i_pass1" type="password" name="pass1" placeholder="6-20 caracteres" ></li>
error<li><div id="regPLenError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input id="i_pass2" type="password" name="pass2" placeholder="Repite la contraseña" ></li>
error<li><div id="regPMatchError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="checkbox" name="offers" value="Yes">Quiero recibir las últimas novedades de TopFIT</li>
<li><input id="i_conditions" type="checkbox" name="conditions" value="accepted" >He leído y acepto la política de privacidad.</li>
error<li><div id="regCondError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="button" id="register" value="Crea tu cuenta"></li>
<li><span id="result"></span></li>
</ul>
</form>
</section>
</section>
</body>
</html>
Related
I have this login, access to the database. the problem I have is that it does not insert the fields that I pass through the post.
I attach my codes to the php that sends the information to the database.
El js en los mensajes de error i el index.php
Php send the post in the BD the name is create.php.
<?php
session_start();
include_once 'conexion.php';
$objeto = new Conexion();
$conexion = $objeto->Conectar();
//recepción de datos enviados mediante POST desde ajax
$usuario = (isset($_POST['usuario'])) ? $_POST['usuario'] : '';
$email = (isset($_POST['email'])) ? $_POST['email'] : '';
$password = (isset($_POST['password'])) ? $_POST['password'] : '';
$cpassword = (isset($_POST['cpassword'])) ? $_POST['cpassword'] : '';
$pass = md5($password); //encripto la clave enviada por el usuario para compararla con la clava
encriptada y almacenada en la BD
$consulta = "SELECT * FROM usuarios WHERE email = '$email'";
if(mysqli_num_rows($consulta)) {
echo 'This email already exists';
}
else {
$resultado = $conexion->prepare($consulta);
$resultado->execute();
if($resultado->rowCount() >= 1){
$data = $resultado->fetchAll(PDO::FETCH_ASSOC);
$query = "INSERT into `usuarios` (usuario, email, password)
VALUES ('$usuario', '$email', '$pass')";
}else{
$_SESSION["s_usuario"] = null;
$data=null;
}
}
print json_encode($data);
$conexion=null;
The .js contains form error messages
$('#formLogin').submit(function(e){
e.preventDefault();
var usuario = $.trim($("#usuario").val());
var password =$.trim($("#password").val());
if(usuario.length == "" || password == ""){
Swal.fire({
type:'warning',
title:'Debe ingresar un usuario y/o password',
});
return false;
}else if{
$.ajax({
url:"bd/login.php",
type:"POST",
datatype: "json",
data: {usuario:usuario, password:password},
success:function(data){
if(data == "null"){
Swal.fire({
type:'error',
title:'Usuario y/o password incorrecta',
});
}else{
Swal.fire({
type:'success',
title:'¡Conexión exitosa!',
confirmButtonColor:'#3085d6',
confirmButtonText:'Ingresar'
}).then((result) => {
if(result.value){
window.location.href = "dashboard/index.php";
}
})
}
}
});
}
else{
$.ajax({
url:"bd/registrar.php",
type:"POST",
datatype: "json",
data: {usuario:usuario, password:password},
success:function(data){
if(data == "null"){
Swal.fire({
type:'error',
title:'Error para crear el Usuario',
});
}else{
Swal.fire({
type:'success',
title:'¡Conexión exitosa!',
confirmButtonColor:'#3085d6',
confirmButtonText:'Ingresar'
}).then((result) => {
if(result.value){
window.location.href = "index.php";
}
})
}
}
});
}
});
Index.php
<html>
<head>
<title>Rem la Ràpita - Sign In</title>
<link rel="icon" type="image/png" href="../images/favicon.png" sizes="52x52"/>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="estilos.css">
<link rel="stylesheet" href="plugins/sweetalert2/sweetalert2.min.css">
<link rel="stylesheet" type="text/css" href="fuentes/iconic/css/material-design-iconic-font.min.css">
</head>
<body>
<div class="container-login">
<div class="wrap-login">
<form class="login-form validate-form" id="formLogin" action="bd/create.php" method="post">
<span class="login-form-title">Sign In</span>
<div class="wrap-input100" data-validate = "Usuario incorrecto">
<input class="input100" type="text" id="usuario" placeholder="Nom">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate = "Usuario incorrecto">
<input class="input100" type="text" id="email" placeholder="Email">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate="Password incorrecto">
<input class="input100" type="password" id="password" placeholder="Contrasenya">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate="Password incorrecto">
<input class="input100" type="password" id="cpassword" placeholder="Confirma Contrasenya">
<span class="focus-efecto"></span>
</div>
<div class="container-login-form-btn">
<div class="wrap-login-form-btn">
<div class="login-form-bgbtn"></div>
<button type="submit" name="submit" class="login-form-btn">CREAR USUARI</button>
</div>
</div>
</form>
</div>
</div>
<script src="jquery/jquery-3.3.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="popper/popper.min.js"></script>
<script src="plugins/sweetalert2/sweetalert2.all.min.js"></script>
<script src="codigo_registro.js"></script>
</body>
Attached image of the database structure.
.
Attached image of the error.
<html>
<head>
<title>Rem la Ràpita - Sign In</title>
<link rel="icon" type="image/png" href="../images/favicon.png" sizes="52x52"/>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="estilos.css">
<link rel="stylesheet" href="plugins/sweetalert2/sweetalert2.min.css">
<link rel="stylesheet" type="text/css" href="fuentes/iconic/css/material-design-iconic-font.min.css">
</head>
<body>
<?php
require('dbconnect.php');
// When form submitted, insert values into the database.
if (isset($_REQUEST['username'])) {
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con, $username);
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($con, $email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con, $password);
$query = "INSERT into `usuaris` (username, password, email)
VALUES ('$username', '" . md5($password) . "', '$email')";
$select_email = mysqli_query($con, "SELECT * FROM usuaris WHERE email = '".$_POST['email']."'");
if(mysqli_num_rows($select_email)) {
echo 'This email already exists';
}
//Comprovar si les contrasenyes coincideixen
else if ($_POST["password"] === $_POST["cpassword"]) {
$result = mysqli_query($con, $query);
if ($result) {
echo "You are registered successfully.";
} else {
echo "Click here to ";
}
}
else {
echo "Les Contrasenyes no coincideixen";
}
} else {}
?>
<div class="container-login">
<div class="wrap-login">
<form class="login-form validate-form" method="post">
<span class="login-form-title">Sign In</span>
<div class="wrap-input100" data-validate = "Usuario incorrecto">
<input class="input100" type="text" name="username" placeholder="Nom" required="required">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate = "Usuario incorrecto">
<input class="input100" type="text" name="email" placeholder="Email" required="required">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate="Password incorrecto">
<input class="input100" type="password" name="password" placeholder="Contrasenya" required="required">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate="Password incorrecto">
<input class="input100" type="password" name="cpassword" placeholder="Confirma Contrasenya" required="required">
<span class="focus-efecto"></span>
</div>
<div class="container-login-form-btn">
<div class="wrap-login-form-btn">
<div class="login-form-bgbtn"></div>
<button type="submit" class="login-form-btn">CREAR USUARI</button>
</div>
</div>
</form>
</div>
</div>
<script src="jquery/jquery-3.3.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="popper/popper.min.js"></script>
<script src="plugins/sweetalert2/sweetalert2.all.min.js"></script>
<script src="codigo_registro.js"></script>
</body>
</html>
I have modified the code and now I get the following errors.
enter image description here
i'm trying to add IconCaptcha (https://github.com/fabianwennink/IconCaptcha-Plugin-jQuery-PHP#installation) to a contact form.
I managed to implement it with success on the web page. But whenever i hit the SUBMIT button (with the other fields well filled) the form is sent. Even if i hit the wrong captcha... Or no captcha at all.
Here is the contact.php page code :
<?php
session_start();
require('IconCaptcha-PHP/src/captcha-session.class.php');
require('IconCaptcha-PHP/src/captcha.class.php');
IconCaptcha::setIconsFolderPath('../assets/icons/');
IconCaptcha::setIconNoiseEnabled(true);
if(!empty($_POST)) {
if(IconCaptcha::validateSubmission($_POST)) {
$captchaMessage = 'Le message a bien été envoyé!';
} else {
$captchaMessage = json_decode(IconCaptcha::getErrorMessage())->error;
}
}
?>
<!doctype html>
<!--
* IconCaptcha Plugin: v2.5.0
* Copyright © 2017, Fabian Wennink (https://www.fabianwennink.nl)
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
-->
<html>
<head>
<!--FORMAT-->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!--STYLES-->
<link href="css/styles.css" rel="stylesheet" type="text/css">
<link href="css/bootstrap-4.3.1.css" rel="stylesheet" type="text/css">
<!-- IconCaptcha stylesheet -->
<link href="IconCaptcha-PHP/assets/css/icon-captcha.min.css" rel="stylesheet" type="text/css">
<script src="http://use.edgefonts.net/montserrat:n4:default.js" type="text/javascript"></script>
<!--SCRIPTS BOOTSTRAP-->
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap-4.3.1.js"></script>
<body>
<section id="contact" class="section-orange">
<div class="container-fluid" justify-content="center" style="width: 90%">
<!-- DEBUT FORMULAIRE CONTACT -->
<?php
if(isset($captchaMessage)) {
echo '<b>Captcha Message: </b>' . $captchaMessage;
}
?>
<form id="reused_form" role="form" method="post" action="envoiformulaire.php">
<div class="row">
<div class="col-md-6 form-group">
<label for="first_name"></label>
<input id="firstname" name="first_name" type="text" class="form-control" placeholder="Prénom" required="required">
</div>
<div class="col-md-6 form-group">
<label for="last_name"></label>
<input id="lastname" name="last_name" type="text" class="form-control" placeholder="NOM" required="required">
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<label for="email"></label>
<input id="email" name="email" type="email" class="form-control" placeholder="Courriel" required="required">
</div>
<div class="col-md-6 form-group">
<label for="telephone"></label>
<input id="telephone" type="tel" name="telephone" onkeyup="formatte(this,2)" onkeypress="return isNumberKey(event)" class="form-control" placeholder="Téléphone" required="required" minlength="14" maxlength="14">
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="comments"></label>
<textarea id="message" name="comments" class="form-control" placeholder="Message (400 caractères maximum)" maxlength="400" rosws="4" required="required"></textarea>
</div>
<div class="col-md-12 form-group">
<div class="captcha-holder"></div>
</div>
<div class="col-md-12 form-group">
<br> <input type="submit" id="btnContactUs" class="btn btn-success btn-send" value="Envoyer le message">
</div>
</div>
</form>
<script src="IconCaptcha-PHP/assets/js/icon-captcha.min.js" type="text/javascript"></script>
<!-- Initialize the IconCaptcha -->
<script async type="text/javascript">
$(window).ready(function() {
$('.captcha-holder').iconCaptcha({
theme: ['light'],
fontFamily: '',
clickDelay: 500,
invalidResetDelay: 3000,
requestIconsDelay: 1500,
loadingAnimationDelay: 1500, // How long the fake loading animation should play.
hoverDetection: true,
showCredits: 'show',
enableLoadingAnimation: false,
validationPath: 'IconCaptcha-PHP/src/captcha-request.php',
messages: {
header: "Vous devez choisir, « …but, choose wiesly! »",
correct: {
top: "« You have chosen… wisely. »",
bottom: "Félicitations! Vous n'êtes pas un robot."
},
incorrect: {
top: "« You chose poorly! »",
bottom: "Oups! Mauvaise image."
}
}
})
.bind('init.iconCaptcha', function(e, id) {
console.log('Event: Captcha initialized', id);
}).bind('selected.iconCaptcha', function(e, id) {
console.log('Event: Icon selected', id);
}).bind('refreshed.iconCaptcha', function(e, id) {
console.log('Event: Captcha refreshed', id);
}).bind('success.iconCaptcha', function(e, id) {
console.log('Event: Correct input', id);
}).bind('error.iconCaptcha', function(e, id) {
console.log('Event: Wrong input', id);
});
});
</script>
<!-- FIN FORMULAIRE CONTACT -->
</div>
</section>
</body>
</html>
Here is the PHP function envoiformulaire.php to send the form :
<?php
header('Content-Type: text/html; charset=utf-8');
if(isset($_POST['email'])) {
$email_to = "mail#mail.com";
$email_subject = "Nouveau message web";
function died($error) {
echo "Oups! Une ou plusieurs erreurs se trouvent dans votre formulaire.<br>";
echo $error."<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('Oups! Un problème est survenu avec votre formulaire.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp ='/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'Le courriel saisi ne semble pas valide.<br />';
}
$phone_exp = "/^(\d\d\s){4}(\d\d)$/";
if(!preg_match( $phone_exp,$telephone)) {
$error_message .= 'Le numéro de téléphone saisi ne semble pas valide.<br />';
}
$string_exp = "/^[A-Za-z àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ.'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'Le prénom saisi ne semble pas valide.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'Le nom saisi ne semble pas valide.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'Le message saisi ne semble pas valide.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Ci-après le formulaire complété.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Prénom: ".clean_string($first_name)."\n";
$email_message .= "NOM: ".clean_string($last_name)."\n";
$email_message .= "Courriel: ".clean_string($email_from)."\n";
$email_message .= "Téléphone: ".clean_string($telephone)."\n";
$email_message .= "Message: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'Content-Type: text/plain; charset="utf-8"'.
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
My guess is that on the contact page when i hit the SUBMIT button it activates the PHP to send the form without the CAPTCHA (method=post action="envoiformulaire.php").
I may have to add "something" to make the SUBMIT button available only with the captcha completed. But i haven't figured how to do it.
Could someone give me a hint ?
Best regards,
Frédéric.
I was in contact with the creator of icon captcha. He helped me a lot, actually more than i expected.
First mistake, i put a part of the PHP validation code page on the contact form :
if(!empty($_POST)) {
if(IconCaptcha::validateSubmission($_POST)) {
$captchaMessage = 'Le message a bien été envoyé!';
} else {
$captchaMessage = json_decode(IconCaptcha::getErrorMessage())->error;
}
}
It should to go from contact.php to envoiformulaire.php .
After that he helped me with my numbnuts php skills...
On the top of the contact page, the following code should be added :
<?php
session_start();
require('IconCaptcha-PHP/src/captcha-session.class.php');
require('IconCaptcha-PHP/src/captcha.class.php');
IconCaptcha::setIconsFolderPath('../assets/icons/');
IconCaptcha::setIconNoiseEnabled(true);
?>
And add this code (ADD) in the envoiformulaire.php :
<?php
session_start(); // ADD THIS
header('Content-Type: text/html; charset=utf-8');
require('IconCaptcha-PHP/src/captcha-session.class.php'); // ADD THIS
require('IconCaptcha-PHP/src/captcha.class.php'); // ADD THIS
IconCaptcha::setIconsFolderPath('../assets/icons/'); // ADD THIS
IconCaptcha::setIconNoiseEnabled(true); // ADD THIS
if(isset($_POST['email'])) {
$email_to = "mail#mail.com";
$email_subject = "Nouveau message web";
function died($error) {
echo "Oups! Une ou plusieurs erreurs se trouvent dans votre formulaire.<br>";
echo $error."<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('Oups! Un problème est survenu avec votre formulaire.');
}
// ADD THIS
if(!IconCaptcha::validateSubmission($_POST)) {
died('ADD YOUR ERROR MESSAGE HERE');
}
...
And now, it works great, thank you Fabian !
I hope this post will help someone in the futur.
Frédéric.
I'm trying to make a contact form with Ajax, php and Jquery for my last study project (php with mvc architecture). I have some questions about it:
my contact form is ok: I receive emails! But I am not sure that is really an Ajax request even if I use the $.ajax() because in my terminal there is no XHR request...
I would like to show a message when email is send like "Thanks for your message" but the message appear only for one second and the page is refreished so all informations are cleaned. I tryed with a e.preventDefault() but when I use it, I don't receive the email.
Thanks for your answers and you help.
contat view:
<section class="form_container">
<form class="contact_form" id="contact_form" method="post" action="index.php?action=contact">
<input class="firstname form" type="text" name="firstname" placeholder="Nom" id="firstname" required>
<span class="error-message"></span><br/>
<input class="lastname form" type="text" name="lastname" placeholder="Prénom" id="lastname" required>
<span class="error-message"></span><br/>
<input class="email form" type="text" name="email" placeholder="Email" id="email" required>
<span class="error-message"></span><br/>
<input class="object form" type="text" name="object" placeholder="Objet" id="object" required>
<span class="error-message"></span><br/>
<textarea class="content form" name="content" placeholder="Votre message" id="content" cols="30" rows="10" required></textarea>
<span class="error-message"></span><br/>
<input class="envoyer form" type="submit" name="submit" value="Envoyer" id="submit"><br/>
</form>
<div id="msg-ok">Merci. Votre message a bien été envoyé.</div>
<div id="msg-notok">Merci de renseigner correctement tous les champs .</div>
</section>
contact_form.js:
// send messages with Ajax
'use strict';
$('#contact_form').submit(function() {
nom = $(this).find("#firstname").val();
prenom = $(this).find("#lastname").val();
email = $(this).find("#email").val();
object = $(this).find("#object").val();
message = $(this).find("#content").val();
$.ajax({
type: "POST",
data: {
nom:nom,
prenom:prenom,
email:email,
object:object,
content:content
},
url: 'http://www.projet-5.pauline-superweb.com/index.php?action=contact',
success: function(data) {
$("#contact_form").hide();
$('#msg-ok').fadeIn();
},
error: function() {
$('#msg-notok').fadeIn();
}
})
});
});
php code in my controller:
function contact()
{
if (isset($_POST['submit'])) {
$e = array();
$e['error'] = "Formulaire non valide";
if(isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['object']) && isset($_POST['content']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$e['email_invalide'] = "email_invalide";
} else {
$e['error'] = 'Ok';
$nom = $_POST['firstname'];
$prenom = $_POST['lastname'];
$email = $_POST['email'];
$object = $_POST['object'];
$content = $_POST['content'];
$to = 'contact.super.web#gmail.com';
$sujet = $object;
$message = $content;
$headers = 'From ' . $nom . ' ' . $prenom . ' ' . $email;
mail($to, $sujet, $message, $headers);
}
}
ob_start();
include('views/frontend/site/contactView.php');
$content = ob_get_clean();
require("views/frontend/site/template.php");
}
change this
<input class="envoyer form" type="submit" name="submit" value="Envoyer" id="submit">
to
<input class="envoyer form" type="button" name="submit" value="Envoyer" id="submit">
and change
$('#contact_form').submit(function() {
to
$('#submit').click(function() {
Sorry for the vague title, but this behaviour is pretty hard to explain.
I have a form where I enter some information. When the user click the submit button (values "programma"), I call a javascript. I check that the info are correct and use AJAX to add a record in my local database. The strange behaviour is the following:
I fill up the form. The record doesn't exist in my DB. Everything works correctly and my record is inserted. Success: I write in the span tag "Esecuzione registrata correttamente!"
Then I try to insert the same record. Since it exists in my DB, the error gets notified correctly in my span: "Esiste un condannato con gli stessi dati"
At this point my form is still full of text, if the user want to correct his mistake and insert a non-existing record. What happens is that, when I change some input (and I'm sure that record doesn't exist in my DB) and click the submit button, literally nothing happens. I still see my error message "Esiste un condannato con gli stessi dati", even if I saw in my console that my AJAX worked correctly
programma.php (what you see in my screenshot)
<?php
session_start();
if(!isset($_SESSION["nickname"]) && !isset($_SESSION["password"]) ) {
header("location: index.php");
exit();
}
else
{
echo "<p> Sessione di ".$_SESSION["nickname"]." con password ".$_SESSION["password"]." </p>";
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="programma.css">
<style type="text/css">
.container {
width: 500px;
clear: both;
}
.container text {
width: 100%;
clear: both;
}
</style>
<title>RIPconvicts - Programma esecuzione</title>
</head>
<body>
<?php require 'snippets/menu.php'; ?>
<form>
<fieldset class="centered">
<legend>Programma nuova esecuzione</legend>
<label for="nome"> Nome* </label> <br>
<input type="text" name="nome" id="nome"> <br> <br>
<label for="cognome"> Cognome* </label> <br>
<input type="text" name="cognome" id="cognome"> <br> <br>
<label for="classe"> Classe* </label> <br>
<input type="text" name="classe" id="classe"> <br> <br>
<label for="materia"> Materia* </label> <br>
<input type="text" name="materia" id="materia"> <br> <br>
<label for="data">Data* </label> <br>
<input type="date" name="data" id="data"> <br> <br>
Note <br>
<textarea name="note" id="note" rows="6" cols="50"> </textarea> <br> <br>
<span id="avviso" style="color:red"></span> <br>
<input type="button" onclick="programma_esecuzione()" value="Programma">
</fieldset>
</form>
<?php require 'snippets/footer.php'; ?>
<script>
function programma_esecuzione() {
// Verifica che tutti i campi necessari siano stati riempiti
document.getElementById("avviso").innerHTML = "";
var nomi = ["nome", "cognome", "classe", "materia"];
var campi_mancanti = "";
for(var i=0; i<nomi.length-1; i++) {
if(document.getElementById(nomi[i]).value == "") {
campi_mancanti+=" "+nomi[i];
}
}
if(!Date.parse( document.getElementById("data").value )) {
campi_mancanti+=" data";
}
// Se ci sono campi mancanti, ritorna alla pagina principale
if(campi_mancanti!="") {
window.alert("Riempire i seguenti campi mancanti:"+campi_mancanti);
return;
}
// Se tutti i campi necessari ci sono, allora è possibile richiedere l'aggiunta del record
var xhttp;
xhttp = new XMLHttpRequest();
var nome = document.getElementById("nome").value;
var cognome = document.getElementById("cognome").value;
var classe = document.getElementById("classe").value;
var materia = document.getElementById("materia").value;
var data = document.getElementById("data").value;
var note = document.getElementById("note").value;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var risposta = this.responseText;
if(risposta.indexOf("Esecuzione registrata correttamente!") > -1) {
// Svuota tutti i campi
document.getElementById("nome").value = "";
document.getElementById("cognome").value = "";
document.getElementById("classe").value = "";
document.getElementById("materia").value = "";
document.getElementById("data").value = "";
document.getElementById("note").value = "";
}
document.getElementById("avviso").innerHTML = risposta;
}
};
xhttp.open("POST", "./snippets/programma_esecuzione.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("nome="+nome+"&cognome="+cognome+"&classe="+classe+"&materia="+materia+"&data="+data+"¬e="+note);
}
</script>
</body>
</html>
programma_esecuzione.php (where I execute my query)
<?php
//Include
require 'connetti_a_DB.php';
// Variabili per il login
$nome = $_POST["nome"];
$cognome = $_POST["cognome"];
$classe = $_POST["classe"];
$materia = $_POST["materia"];
$data = $_POST["data"];
$note = $_POST["note"];
/*echo $nome."<br>";
echo $cognome."<br>";
echo $classe."<br>";
echo $materia."<br>";
echo $data."<br>";
echo $note."<br>";*/
// Inizia una sessione
session_start();
$username = $_SESSION["nickname"];
$password = $_SESSION["password"];
// Stabilire e chiudere connessione
$conn = connetti_a_DB($username, $password);
// Verifica se c'è un record "clone"
$nome_completo = $nome." ".$cognome;
$sql = " SELECT *
FROM `lista`
WHERE `NOME_COMPLETO`='$nome_completo' OR
`CLASSE`='$classe' OR
`MATERIA` ='$materia' OR
`DATA` ='$data'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
echo 'Esiste un condannato con gli stessi dati';
}
else
{
$sql = "INSERT INTO `ripconvicts`.`lista` (`ID`, `NOME_COMPLETO`, `CLASSE`, `MATERIA`, `DATA`, `NOTE`)
VALUES (NULL, '$nome_completo', '$classe', '$materia', '$data', '$note')";
$result = $conn->query($sql);
echo "Esecuzione registrata correttamente!";
}
$conn->close();
// Salta alla pagina iniziale
//header("location: ../programma.php");
//exit();
?>
I got a simple email form that sends mails correctly except there is no data inside them. It also sends emails twice. What could be the cause of this?
contact.php :
<form class="contact-form columns_padding_5" method="post" action="mail/mail-send.php">
<div class="col-sm-6">
<p class="contact-form-name">
<label for="name">Naam<span class="required">*</span></label>
<input type="text" aria-required="true" size="30" value="" name="name" id="name" class="form-control" placeholder="Naam">
</p>
</div>
<div class="col-sm-6">
<p class="contact-form-subject">
<label for="subject">Onderwerp<span class="required">*</span></label>
<input type="text" aria-required="true" size="30" value="" name="subject" id="subject" class="form-control" placeholder="Onderwerp">
</p>
</div>
<div class="col-sm-6">
<p class="contact-form-phone">
<label for="email">Email-adres<span class="required">*</span></label>
<input type="email" aria-required="true" size="30" value="" name="email" id="email" class="form-control" placeholder="Email-adres">
</p>
</div>
<div class="col-sm-6">
<p class="contact-form-email">
<label for="phone">Telefoonnummer<span class="required">*</span></label>
<input type="text" aria-required="true" size="30" value="" name="phone" id="phone" class="form-control" placeholder="Telefoonnummer">
</p>
</div>
<div class="col-sm-12">
<p class="contact-form-message">
<label for="message">Bericht</label>
<textarea aria-required="true" rows="6" cols="45" name="message" id="message" class="form-control" placeholder="Bericht"></textarea>
</p>
</div>
<div class="col-sm-12">
<p class="contact-form-submit topmargin_30">
<button type="submit" id="contact_form_submit" name="contact_submit" class="theme_button wide_button color1">Verstuur bericht</button>
<button type="reset" id="contact_form_reset" name="contact_reset" class="theme_button wide_button">Leeg formulier</button>
</p>
</div>
</form>
mail-send.php :
<?PHP
require_once("../phpMailer/class.phpmailer.php");
$isValid = true;
if(isset($_POST['name']) && isset($_POST['subject']) && isset($_POST['email']) && isset($_POST['message']))
{
$name = $_POST['name'];
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];
$phone = $_POST['phone'];
$mail = new PHPMailer;
$mail->From = $email;
$mail->FromName = $name;
$mail->addAddress("email#live.nl"); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$texts = 'Er is een aanvraag op de website van website<br /> <br />
<b>Naam:</b> '.$name.'<br />
<b>E-mail adres:</b> '.$email.'<br />
<b>Onderwerp:</b> '.$subject.'<br />
<b>Telefoonnummer:</b>'.$phone.'<br />
<b>Vragen / Opmerkingen:</b> '.$message.'<br /><br /><br />
';
$handtekening = '
<table border="0" width="100%" cellspacing="0" cellpadding="0" style="font-family:calibri;color: #5C5C5C; font-size:10pt;line-height:22px;">
<tr>
<td width="160" valign="top" style="font-family:calibri;padding-left:10px;padding-top:20px;">
[contents]
</td>
</tr>
<tr>
<td width="160" valign="top" style="font-family:calibri;padding-left:10px;padding-top:20px;">
<br><br>Met vriendelijke groet,<br><br>
Helpdesk<br>
<b>website</b><br>
<p></p>
</td>
</tr>
</table>
<table height="120" border="0" width="100%" cellspacing="0" cellpadding="0" style="font-family:calibri;color: #5C5C5C; font-size:10pt;line-height:22px;">
<tr>
<td width="250" valign="top" style="font-family:calibri;padding-left:10px;padding-top:20px;border-top: 1px #000000 dotted; border-bottom: 1px #000000 dotted;">
E:
info#website.nl<br>
T:
0615086609<br>
W:
www.website.nl<br>
</td>
<td align="right" style="font-family:calibri;padding-right:10px;padding-top:5px;border-top: 1px #000000 dotted; border-bottom: 1px #000000 dotted;">
<a href="http://website.nl/" target="_blank" title="Ga naar de website">
<img src="http://website.nl/_extern/website/images/logo/logo.png" alt="Ga naar de website" style="font-family:calibri;text-align:right;margin:0px;padding:10px 0 10px 0;" border="0" width="232">
</a>
</td>
</tr>
<tr>
<td colspan="2" style="font-family:calibri;color:#a3a3a3;font-size:11px;margin-top:6px;line-height:14px;">
<br>Dit e-mailbericht is uitsluitend bestemd voor de geadresseerde. Als dit bericht niet voor u bestemd is, wordt u vriendelijk verzocht dit aan de afzender te melden. website staat door de elektronische verzending van dit bericht niet in voor de juiste en volledige overbrenging van de inhoud, noch voor tijdige ontvangst daarvan. Voor informatie over website raadpleegt u website.<br><br>
</td>
</tr>
</table>';
$contents = preg_replace('/\[contents]/',$texts, $handtekening);
$mail->msgHTML($contents);
$mail->AltBody = $texts;
if(!$mail->send())
{
$isValid = false;
}
$mail = new PHPMailer;
$mail->From = 'info#website.nl';
$mail->FromName = 'website';
$mail->addAddress($email); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Bedankt voor uw aanvraag bij website';
$texts = 'Geachte heer/mevrouw '.$naam.',<br /><br />
Hartelijk dank voor uw aanvraag bij website<br />
Wij reageren zo spoedig mogelijk op uw aanvraag.<br /><br />
Uw gegevens worden nooit aan derden ter hand gesteld.
';
$contents = preg_replace('/\[contents]/',$texts, $handtekening);
$mail->msgHTML($contents);
$mail->AltBody = $texts;
if(!$mail->send())
$isValid = false;
}
if($isValid == true) {
$result["submit_message"] = _msg_send_ok;
} else {
$result["submit_message"] = _msg_send_error;
}
if($_POST["name"]=="" || $_POST["name"]==_def_name)
$result["error_name"] = _msg_invalid_data_name;
if($_POST["email"]=="" || $_POST["email"]==_def_email || !preg_match("#^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$#", $_POST["email"]))
$result["error_email"] = _msg_invalid_data_email;
if($_POST["message"]=="" || $_POST["message"]==_def_message)
$result["error_message"] = _msg_invalid_data_message;
$result['isValid'] = $isValid;
echo json_encode($result);
This is the ajax part that processes the contact form:
//function that initiating template plugins on document.ready event
function documentReadyInit() {
///////////
//Plugins//
///////////
//contact form processing
jQuery('form.contact-form').on('submit', function( e ){
e.preventDefault();
var $form = jQuery(this);
jQuery($form).find('span.contact-form-respond').remove();
//checking on empty values
jQuery($form).find('[aria-required="true"], [required]').each(function(index) {
if (!jQuery(this).val().length) {
jQuery(this).addClass('invalid').on('focus', function(){jQuery(this).removeClass('invalid')});
}
});
//if one of form fields is empty - exit
if ($form.find('[aria-required="true"], [required]').hasClass('invalid')) {
return false;
}
//sending form data to PHP server if fields are not empty
var request = $form.serialize();
var ajax = jQuery.post( "mail/mail-send.php", request )
.done(function( data ) {
jQuery($form).find('[type="submit"]').attr('disabled', false).parent().append('<span class="contact-form-respond highlight">'+data+'</span>');
})
.fail(function( data ) {
jQuery($form).find('[type="submit"]').attr('disabled', false).parent().append('<span class="contact-form-respond highlight">Mail cannot be sent. You need PHP server to send mail.</span>');
})
});
And finally my config file where some data is set like the success/failure messages:
config.php :
<?php
define('_from_name', 'website');
define('_from_email', 'info#website.nl');
define('_to_name', '');
define('_to_email', 'website#live.nl');
define('_smtp_host', '');
define('_smtp_username', '');
define('_smtp_password', '');
define('_smtp_port', '');
define('_smtp_secure', ''); //ssl or tls
define('_subject_email', 'website: Contactaanvraag');
define('_def_name', 'Uw Naam *');
define('_def_email', 'Uw Emailadres *');
define('_def_phone', 'Uw Telefoonnummer');
define('_def_message', 'Bericht *');
define('_def_message_appointment', 'Aanvullende informatie');
define('_msg_invalid_data_name', 'Voer een naam in.');
define('_msg_invalid_data_email', 'Voer een geldig emailadres in.');
define('_msg_invalid_data_message', 'Voer een bericht in.');
define('_msg_send_ok', 'Bedankt voor uw bericht!');
define('_msg_send_error', 'Dit bericht kan niet worden verzonden.');
?>
The correct behaviour should be:
One confirmation mail to the mail the customer filled in, and one mail which the customer wrote to the company.
Now I receive two mails (with no data in them) for the company and the customer receives nothing.
Here you can see the mail is sent correctly:
And these are the two success messages I get (in json, I don't know how to decode it)
if(!$mail->send())
{
$isValid = false;
}
$mail = new PHPMailer;
$mail->From = 'info#website.nl';
$mail->FromName = 'website';
$mail->addAddress($email); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Bedankt voor uw aanvraag bij website';
$texts = 'Geachte heer/mevrouw '.$naam.',<br /><br />
Hartelijk dank voor uw aanvraag bij website<br />
Wij reageren zo spoedig mogelijk op uw aanvraag.<br /><br />
Uw gegevens worden nooit aan derden ter hand gesteld.
';
$contents = preg_replace('/\[contents]/',$texts, $handtekening);
$mail->msgHTML($contents);
$mail->AltBody = $texts;
if(!$mail->send())
{
$isValid = false;
}
You're testing if(!$mail->send()) twice.