javascript to get previous url of visitor from contact form - javascript

I want to track my prospects from which URL(like fb, g+ or mailer) they have visited my website.This is all is for understanding visitor for better digital marketing.
My Fiddle: http://jsfiddle.net/dSp4g/
Please help me with code as below
Thanks in advance
HTML
<div class="form-group">
<label for="exampleInputEmail">Full name</label>
<input type="text" class="form-control " id="exampleInputName" placeholder="Enter your full name" style="color:#000 !important;">
</div>
<div class="form-group">
<input type="hidden" class="form-control " id="sourcecode">
</div>
<div class="form-group last">
<button class="mailbtn">Submit</button>
</div>
JS
$('.mailbtn').live('click',function(){
name = $('#exampleInputName').val();
sc = $('#sourcecode').val();
$(document).ready(function() {
if (sourcecode = $.parsequery().s)
{
$("#source").val(sourcecode); }
});
$.ajax({
type: "POST",
async : false,
url: "mail.php",
data: { name:name, sourcecode:sc}
})
.done(function( msg ) {
$('.mail_middle').html('');
$('.mail_middle').html('We will call you to confirm your delivery address.Thank you.');
return false;
});
});
mail.php
<?php
$to = array("my_email1","my_email2");
$message .= "<table border='1'>";
$message .= "<tr><td>Name </td><td>".$_POST['name']."</td></tr>";
$message .= "<tr><td>Source </td><td>".$_POST['sc']."</td></tr>";
$message .= "</table>";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= 'from: '.$from .'' . "\r\n" .
'Reply-To: '.$from.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
foreach($to as $row)
{
mail($row,$subject,$message,$headers);
}
echo "Mail Sent.";
die;
?>

Change $_POST['sc']
$message .= "<tr><td>Source </td><td>".$_POST['sc']."</td></tr>";
to $_POST['sourcecode']
$message .= "<tr><td>Source </td><td>".$_POST['sourcecode']."</td></tr>";
as sourcecode is the name (wheresc is the value)
data: { name:name, sourcecode:sc}

HTML
add a
<input type="hidden" name="the_ref" value="<?= $_SERVER['HTTP_REFERER']; ?>">
JS
modify to
data: { name:name, sourcecode:sc, the_ref:ref}
PHP
add a
$message .= "<tr><td>Visitor came from </td><td>".$_POST['the_ref']."</td></tr>";
your jquery implementation fails because in your php you are trying to read the $_POST['sc'] instead of $_POST['sourcecode']

Related

echo php form validation with ajax

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

force to validate a checkbox

This script below allow to validate all checkox inside a form.
My problem, I need to have just one to validate.
What is the element to change to verify if just one chabox is validated ?
<?php
$display_option .= '<div class="form-group ProductsInfoOptionCheckbox" options>';
$display_option .= '<label class="control-label ProductsInfoOptionCheckbox" for="input-option' . $option['products_option_id'] . '">' . $option['name'] . '</label>';
foreach ($option['products_option_value'] as $t => $option_value) {
$display_option .= '<div class="checkbox">';
$display_option .= '<ul class="list-unstyled ProductsInfoOptionCheckbox">';
$display_option .= '<li class="ProductsInfoOptionCheckbox">';
$display_option .= HTML::checkboxField('id[' . $option['products_option_id'] . ']', $option_value['products_option_value_id'], $checked_attribute, 'required');
}
$display_option .= '<div>';
echo $display_option;
?>
<script>
$(function(){
var requiredCheckboxes = $('.options :checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
} else {
requiredCheckboxes.attr('required', 'required');
}
});
});
</script>
I solved this by using:
$display_option .= '<div class="form-group ProductsInfoOptionCheckbox options">';

HTML/PHP email form [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
My mailer form isn't works. If it possible please take a look and give me some answer to make it work. <3
Here is the PHP:
<?php
if($_POST) {
$EmailFrom = "blah";
$EmailTo = "blah";
$Subject = "blah";
$Name1 = $_POST['Name1'];
$Name2= $_POST['Name2'];
$Name3 = $_POST['Name3'];
$Name4 = $_POST['Name4'];
$Name5 = $_POST['Name5'];
$Email = $_POST['Email'];
$TeamName = $_POST['TeamName'];
$Message = $_POST['Message'];
$Body = "";
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Player1: ";
$Body .= $Name1;
$Body .= "\n";
$Body .= "Player2: ";
$Body .= $Name2;
$Body .= "\n";
$Body .= "Player3: ";
$Body .= $Name3;
$Body .= "\n";
$Body .= "Player4: ";
$Body .= $Name4;
$Body .= "\n";
$Body .= "Player5: ";
$Body .= $Name5;
$Body .= "\n";
$Body .= "TeamName: ";
$Body .= $TeamName;
$Body .= "\n";
$Body .= "Megjegyzes: ";
$Body .= $Message;
$Body .= "\n";
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
}
?>
I tried many methods but seems like I don't really know something.
In HTMLI used this method:
Here is the HTML:
<form action="contact.php" class="contact-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="Name1" class="form-control" id="name1" placeholder="Játékos 1">
<input type="text" name="Name2" class="form-control" id="name2" placeholder="Játékos 2">
<input type="text" name="Name3" class="form-control" id="name3" placeholder="Játékos 3">
<input type="text" name="Name4" class="form-control" id="name4" placeholder="Játékos 4">
<input type="text" name="Name5" class="form-control" id="name5" placeholder="Játékos 5">
<p> Még <strong> 16 </strong> csapat számára van hely! </p>
</div>
<div class="col-md-6">
<input type="email" name="Email" class="form-control" id="Email" placeholder="Email">
<input type="text" name="TeamName" class="form-control" id="TeamName" placeholder="Csapatnév">
<textarea class="form-control" id="Message" rows="25" cols="10" placeholder=" Megjegyzés (nem kötelező)"></textarea>
<button type="button" class="btn btn-default submit-btn form_submit">Jelentkezés</button>
<p> A jelentkezéssel elfogadjátok a verseny szabályzatát és feltételeit. </p>
</div>
</div>
</form>
What can be wrong? Thanks for your reply!
<?php
if(isset($_POST["submit"])) {
$EmailFrom = "blah";
$EmailTo = "blah";
$Subject = "blah";
$Name1 = $_POST['Name1'];
$Name2= $_POST['Name2'];
$Name3 = $_POST['Name3'];
$Name4 = $_POST['Name4'];
$Name5 = $_POST['Name5'];
$Email = $_POST['Email'];
$TeamName = $_POST['TeamName'];
$Message = $_POST['Message'];
$Body = "";
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Player1: ";
$Body .= $Name1;
$Body .= "\n";
$Body .= "Player2: ";
$Body .= $Name2;
$Body .= "\n";
$Body .= "Player3: ";
$Body .= $Name3;
$Body .= "\n";
$Body .= "Player4: ";
$Body .= $Name4;
$Body .= "\n";
$Body .= "Player5: ";
$Body .= $Name5;
$Body .= "\n";
$Body .= "TeamName: ";
$Body .= $TeamName;
$Body .= "\n";
$Body .= "Megjegyzes: ";
$Body .= $Message;
$Body .= "\n";
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
}
?>

Receiving unfilled contact forms on email

so in the last 2 months my website is online, i have been received 2 normal email from my contact form and like 30 empty unfilled form emails. I also use validator http://faireware.de/js/jquery.form-validation-and-hints.js.
The weird is that i don't get these empty for emails when i i.e. dont fill an form and press send. It happens automaticly somehow... a spam bots or something, could it be?
My HTML code is:
<form method="post" action="contactengine.php">
<div class="field required">
<p>Name<br>
<input class="text verifyText hint" name="name" type="text" size="25" title="*Ihr Name..."></p>
</div><!--/field-->
<div class="field required ">
<p>E-Mail<br>
<input class="email verifyMail hint " name="email" type="text" size="25" title="*Ihre E-Mail-Adresse..."></p>
</div><!--/field-->
<div class="field required ">
<p>Nachricht<br>
<textarea name="message" rows="50" cols="50" title="*Schreiben Sie Ihre Nachricht..." class="hint "></textarea></p>
</div><!--/field-->
<p><input class="submit" type="submit" value="Senden"></p>
</form>
and my contactengine.php is:
<?php
$Subject = "Kontaktformular - FaireWare";
$Name = Trim(stripslashes($_POST['name']));
$Email = Trim(stripslashes($_POST['email']));
$Message = Trim(stripslashes($_POST['message']));
$EmailFrom = $Email;
$EmailTo = "info#faireware.de";
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n\n";
$Body .= "E-Mail: ";
$Body .= $Email;
$Body .= "\n\n";
$Body .= "Nachricht: ";
$Body .= "\n";
$Body .= $Message;
$Body .= "\n\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: $Email");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.html\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
And the empty email forms do come like this:
Name:
E-Mail:
Nachricht:
Does it do it automaticly and how can it surpass validation...? I don't know PHP and very little java, so does anyone have any idea where the problem could be?
Thank you!
You can try this, i have modified your code with basic server side validations.
<?
if(count($_POST) > 0)
{
$Subject = "Kontaktformular - FaireWare";
$Name = trim(stripslashes($_POST['name']));
$Email = trim(stripslashes($_POST['email']));
$Message = trim(stripslashes($_POST['message']));
$EmailTo = "info#faireware.de";
$validationOK = true;
if(empty($Name) || empty($Email) || empty($Message)){
$validationOK = false;
}
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
else
{
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n\n";
$Body .= "E-Mail: ";
$Body .= $Email;
$Body .= "\n\n";
$Body .= "Nachricht: ";
$Body .= "\n";
$Body .= $Message;
$Body .= "\n\n";
$headers = 'From: $Email' . "\r\n";
// send email
$success = mail($EmailTo, $Subject, $Body, $headers);
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.html\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
}
}
?>
What i have changed?
Add starting check if $_POST array not 0 and than add basic validation with empty(). If any one field empty email will not send else you will get the email.
Try to update your server-side code to unbreakable to avoid spam. Here is some suggestions.
Google Recaptcha
Honeypot Technique
Also do server side isset check.
if(isset($_POST['name'])){
// Save the data or do the further processing
}
Suggestion: Do not depend on client side validations when developing secure applications.

Using AJAX with a contact form to remove page reload

I have seen lots of questions about this on here and have taken the code I have now from several answers.
But for some reason I cant get it to work and I cant figure out why.
I have a HTML form with the code here:
<form id="quick_contact" name="quick_contact" action="" method="POST">
<div class="input-control text">
<input id="name" name="name" type="text" value="" placeholder="Enter name here">
</div>
<div class="space10"> </div>
<div class="input-control email">
<input id="email" name="email" type="email" value="" placeholder="Enter email address here"/>
</div>
<div class="space10"> </div>
<div class="input-control textarea">
<textarea id="comments" name="comments" placeholder="Enter Comments Here"></textarea>
</div>
<div class="space10"> </div>
<button id="quick_submit" name="quick_submit" onclick="quickContact()">Send</button>
</form>
And I have my jquery here UPDATED as of Thomas' answer:
<script type="text/javascript">
function quickContact(){
$.ajax({
type: "POST",
url: "quick-contact.php",
data:
{
name: $('#name').val().trim(),
email: $('#email').val().trim(),
comments: $('#comments').val().trim(),
},
success: function(html) {
var submitted = $.trim(html);
if (submitted) {
alert("Thanks for your submission");
$('#quick_contact')[0].reset();
return;
} else {
alert("Failed to submit.");
return false;
}
}
});
};
</script>
And here is the PHP which handles the email side of things in a file called "quick-contact.php again updated as of Thomas' answer:
if(isset($_POST) == true){
$status = 1 // init to one, assume there will not be an error
//Store the entered values in the variables
$name = mysql_escape_string(trim($_POST['name']));
$email = mysql_escape_string(trim($_POST['email']));
$comments = mysql_escape_string(trim($_POST['comments']));
$comments = str_replace('\r\n','<br>',$comments);
// EMAIL HEADERS
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "X-Priority: 3\n";
$headers .= "X-MSMail-Priority: Normal\n";
$headers .= "X-Mailer: php\n";
$headers .= "From: *****<*****#l*****>\n";
//SEND EMAIL TO BRANCH
// EMAIL TITLE
$subject = $name . " " . get_content(3344);
//message
$message1 = "<style type=\"text/css\">";
$message1 .= "div { font-family: Arial, Verdana, Tahoma; font-size: 10pt; line-height: 120%; }";
$message1 .= "h1 { margin: 0; font-size: 14pt; }";
$message1 .= "h2 { margin: 0; font-size: 12pt; }";
$message1 .= "span { font-size: 9pt; font-weight: bold; }";
$message1 .= "</style>\n";
$message1 .= "<div>";
$message1 .= "<p>" . $name . " " . get_content(3344) . "</p>\n";
$message1 .= "<p>" . get_content(3345) . "</p>\n";
$message1 .= "<p><b>" . ucwords(get_content(2869)) . ":</b> " . $name . "<br />";
$message1 .= "<b>" . ucwords(get_content(27)) . ":</b> " . $email . "<br />";
$message1 .= "<b>" . ucwords(get_content(1258)) . ":</b> " . $comments . "<br />";
$message1 .= "</p>\n";
$message1 .= get_content(893); // King Regards,
$message1 .= "<br /><br />";
$message1 .= "<img src=\"***********\" alt=\"*******\">";
$message1 .= "<br />";
$message1 .= "</div>";
//SEND CUSTOMER AN EMAIL
// EMAIL TITLE
$subject2 = get_content(392);
//message
$message2 = "<style type=\"text/css\">";
$message2 .= "div { font-family: Arial, Verdana, Tahoma; font-size: 10pt; line-height: 120%; }";
$message2 .= "h1 { margin: 0; font-size: 14pt; }";
$message2 .= "h2 { margin: 0; font-size: 12pt; }";
$message2 .= "span { font-size: 9pt; font-weight: bold; }";
$message2 .= "</style>\n";
$message2 .= "<div>";
$message2 .= "<p>" . $name . ",</p>\n";
$message2 .= "<p>" . get_content(392) . "</p>\n";
$message2 .= "<p>" . str_replace("{TEL_NUMBER}", $header_branch_details[0]['Tel'], str_replace("{BRANCH_EMAIL}", $header_branch_details[0]['SalesEmail'], get_content(2764))) . "</p>\n";
$message2 .= get_content(893); // King Regards,
$message2 .= "<br /><br />";
$message2 .= "<img src=\"*********\" alt=\"*********\">";
$message2 .= "<br />";
$message2 .= "</div>";
//Send branch email
$success = mail('***#****.com', $subject, $message1, $headers);
//Send customer email
$success2 = mail($email, $subject2, $message2, $headers);
if (!$success) {
$status = 0;
}
echo $status;
}
Sorry about the mass of code I really hope someone can help me here
Change the submit type to a button type with an onClick event that calls doSomething().
Then, have doSomething() run the ajax call, like so:
function doSomething() {
$.ajax({
type: 'post',
url: 'quick-contact.php',
data:
{
name: $('#name').val().trim(),
email: $('#email').val().trim(),
comments: $('#comments').val().trim(),
},
success: function(html) {
var status = $.trim(html);
if (status) {
alert("Thanks for your submission");
$('#quick_contact')[0].reset();
return;
} else {
alert("Failed to submit.");
return false;
}
}
});
}
Then in your PHP, all you have to do is check if $_POST isset.
if (($_POST)) {
$status = 1; // init to one, assume there will not be an error
$name = $_POST['name'];
//etc, but FILTER the data coming from the client
}
Also, you may want to do something like this near your mail() function:
$success = mail(//etc);
if (!$success) {
$status = 0;
}
echo $status;
If you still have questions, let me know. I'm happy to help.

Categories

Resources