I'm new to PHP and have a problem with the following contact form:
The variable: $empresa = $_POST['empresa']; is not working... and I don't understand where the problem is. When I try to use it in the E-Mail sent, it just doesn't show up.
$received_subject = 'Has sido contactado desde www.company.com por ' . $name . '. Empresa' . $empresa . '.' ;
**This is the PHP I'm using: **
THANKS in advance
<?php
if(!$_POST) exit;
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$empresa = $_POST['empresa'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($comments) == '') {
echo '<div class="error_message">Has olvidado escribir tu mensaje.</div>';
exit();
}
if(trim($name) == '') {
echo '<div class="error_message">Tienes que poner un nombre.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Por favor pon tu dirección de e-mail, para poder ponernos en contacto contigo.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Dirección de e-mail inválida, inténtelo nuevamente.</div>';
exit();
}
$address = "mail#mail.com";
$received_subject = 'Has sido contactado desde www.company.com por ' . $name . '. Empresa' . $empresa . '.' ;
$received_body = "$name te ha contactado desde www.company.com " . PHP_EOL . PHP_EOL;
$received_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$received_reply = "Responder a $name $email o llamar al teléfono: $phone | Empresa: $empresa ";
$message = wordwrap( $received_body . $received_content . $received_reply, 100 );
$header = "From: $email" . PHP_EOL;
$header .= "Reply-To: $email" . PHP_EOL;
if(mail($address, $received_subject, $message, $header)) {
// Email has sent successfully, echo a success page.
echo "<h2>E-Mail enviado con éxito</h2>";
echo "<p>Gracias <strong>$name</strong>, tu mensaje ha sido enviado.</p>";
} else {
echo 'ERROR!';
}
MY form is here:
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset id="contact_form">
<label for="name">
<input type="text" name="name" id="name" placeholder="Nombre *">
</label>
<label for="empresa">
<input type="text" name="empresa" id="empresa" placeholder="Empresa *">
</label>
<label for="email">
<input type="email" name="email" id="email" placeholder="E-Mail *">
</label>
<label for="phone">
<input type="text" name="phone" id="phone" placeholder="Número de teléfono">
</label>
<label for="comments">
<textarea name="comments" id="comments" placeholder="Mensaje *"></textarea>
</label>
<p class="obligatorio"> * = Obligatorio</p>
<input type="submit" class="submit btn btn-default btn-black" id="submit" value="Enviar">
</fieldset>
</form>
If all of your other post variables are working then it sounds like the $_POST['empresa'] variable is not making it to the php page. To debug your script you can either switch your form method to GET to see the query string in the browser url or use a tool like firebug which is a add on for firefox. You will get error on your php page when you switch to the GET method on your html form. Don't worry about that your are just trying to see if the empressa variable is being sent via the http Post request.
Ok your variable dump should show this based on the code your provided
array
'name' => string 'Larry' (length=5)
'empresa' => string 'Lane' (length=4)
'email' => string 'ok#yahoo.com' (length=12)
'phone' => string '123' (length=3)
'comments' => string 'ok' (length=2)
So empresa is making it to the page just fine. I did notice that you do not have an opening form tag for your form? You should have something like this with the names of your file in place of the ones I used for testing of course.
<form name="testform" action="testingpostvariables.php" method="POST">
Place echo $message; after your line of code in your php file
$message = wordwrap( $received_body . $received_content . $received_reply, 100 );
$echo message;
When I did it empresa showed up.
Ok put this code in seperate php file and test it so we can figure out why "empresa" is not showing up. I would also trying refreshing your browser before testing this file to make sure there is no bad cached results.
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset id="contact_form">
<label for="name">
<input type="text" name="name" id="name" placeholder="Nombre *">
</label>
<label for="empresa">
<input type="text" name="empresa" id="empresa" placeholder="Empresa *">
</label>
<label for="email">
<input type="email" name="email" id="email" placeholder="E-Mail *">
</label>
<label for="phone">
<input type="text" name="phone" id="phone" placeholder="Número de teléfono">
</label>
<label for="comments">
<textarea name="comments" id="comments" placeholder="Mensaje *"></textarea>
</label>
<p class="obligatorio"> * = Obligatorio</p>
<input type="submit" class="submit btn btn-default btn-black" id="submit" value="Enviar">
</fieldset>
</form>
<?php
//debug
echo var_dump($_POST);
//debug
if(!$_POST){
echo "NO POST";
//exit;
}
else{
echo "POSTED";
}
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$empresa = $_POST['empresa'];
//impress is posting just fine
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($comments) == '') {
echo '<div class="error_message">Has olvidado escribir tu mensaje.</div>';
exit();
}
if(trim($name) == '') {
echo '<div class="error_message">Tienes que poner un nombre.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Por favor pon tu dirección de e-mail, para poder ponernos en contacto contigo.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Dirección de e-mail inválida, inténtelo nuevamente.</div>';
exit();
}
$address = "mail#mail.com";
$received_subject = 'Has sido contactado desde www.company.com por ' . $name . '. Empresa' . $empresa . '.' ;
//debug
//$empressa is still working fine
$received_body = "$name te ha contactado desde www.company.com " . PHP_EOL . PHP_EOL;
$received_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$received_reply = "Responder a $name $email o llamar al teléfono: $phone | Empresa: $empresa ";
$message = wordwrap( $received_body . $received_content . $received_reply, 100 );
echo $message;
$header = "From: $email" . PHP_EOL;
$header .= "Reply-To: $email" . PHP_EOL;
/*
if(mail($address, $received_subject, $message, $header)) {
// Email has sent successfully, echo a success page.
echo "<h2>E-Mail enviado con éxito</h2>";
echo "<p>Gracias <strong>$name</strong>, tu mensaje ha sido enviado.</p>";
} else {
echo 'ERROR!';
}
*/
This what my result looked like with the empresa value at the end(Lane is the empresa value I entered in the form).
POSTEDLarry te ha contactado desde www.company.com "This is a really long message ok lets see whats going on with this php code it is not sending the empresa variable" Responder a Larry mail#mail.com o llamar al teléfono: 12345678 | Empresa: Lane
Ok in your "custom.js" file you have the following line of code that could be causing some problems.
$.post(action, {
name: $('#name').val(),
empresa: $('#empresa').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(), //remove this comma
There should not be a comma after the last property value try removing that to see if you get the value of empresa from the jquery code. Try it and let me know i
I've solved the issue, by changing the word empresa with something else.
I think there was some sort of collision using this word.
Thanks so much for your help!
Related
I have a completely functional Form that sends mail as it should and all BUT for some reason, when I (try to) submit my message, instead of showing the success or error alert under the form, it opens the sendmail.php page with the messages, without any CSS... It's been 4 days and I'm going crazy. I'm sure it's actually a stupid typo or something but I can't find it, please help.
Screen of the "Success/Alert" display
Here's my sendmail.php:
<?php
$sendto = 'my#email.com';
$subject = 'Message de votre site';
$errormessage = 'Ah, vous avez oublié quelques informations. Réessayez ? ';
$thanks = "Merci pour votre message ! On vous répond aussi vite que possible. ";
$honeypot = "Vous êtes tombé dans le piège ! Si vous êtes humain.e, recommencez ! ";
$emptyname = 'Quel est votre nom ? ';
$emptyemail = 'Quelle est votre adresse mail ? ';
$emptymessage = 'Et votre message ? ';
$alertname = 'Utilisez uniquement un alphabet standard. ';
$alertemail = 'Entrez ce format de mail : <i>name#example.com</i>. ';
$alertmessage = "Vérifiez que vous n 'avez utilisé aucun caractère spécial. ";
$alert = '';
$pass = 0;
function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}
if ( empty($_REQUEST['last']) ) {
if ( empty($_REQUEST['name']) ) {
$pass = 1;
$alert .= "<li>" . $emptyname . "</li>";
$alert .= "<script>jQuery(\"#name\").addClass(\"error\");</script>";
} elseif ( preg_match( "/[][{}()*+?.\\^$|]/", $_REQUEST['name'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertname . "</li>";
}
if ( empty($_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $emptyemail . "</li>";
$alert .= "<script>jQuery(\"#email\").addClass(\"error\");</script>";
} elseif ( !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $alertemail . "</li>";
}
if ( empty($_REQUEST['message']) ) {
$pass = 1;
$alert .= "<li>" . $emptymessage . "</li>";
$alert .= "<script>jQuery(\"#message\").addClass(\"error\");</script>";
} elseif ( preg_match( "/[][{}()*+?\\^$|]/", $_REQUEST['message'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertmessage . "</li>";
}
if ( $pass==1 ) {
echo "<script>$(\".result\").toggle();$(\".result\").toggle().hide(\"fast\").show(\"fast\"); </script>";
echo "<script>$(\".result .alert\").addClass('alert-danger').removeClass('alert-success'); </script>";
echo $errormessage;
echo $alert;
} elseif (isset($_REQUEST['message'])) {
$message = "From: " . clean_var($_REQUEST['name']) . "\n";
$message .= "Email: " . clean_var($_REQUEST['email']) . "\n";
$message .= "Message: \n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
mail($sendto, $subject, $message, $header);
echo "<script>$(\".result\").toggle();$(\".result\").toggle().hide(\"fast\").show(\"fast\");$('#contactForm')[0].reset();</script>";
echo "<script>$(\".result .alert\").addClass('alert-success').removeClass('alert-danger'); </script>";
echo $thanks;
echo "<script>jQuery(\"#name\").removeClass(\"error\");jQuery(\"#email\").removeClass(\"error\");jQuery(\"#message\").removeClass(\"error\");</script>";
echo "<script>$(\".result .alert\").delay(4000).hide(\"fast\");</script>";
die();
echo "<br/><br/>" . $message;
}
} else {
echo "<script>$(\".result\").toggle();$(\".result\").toggle().hide(\"fast\").show(\"fast\");</script>";
echo $honeypot;
}
?>
And HTML:
<form class="form-inline flowuplabels" role="form" method="post" autocomplete="off" id="contactForm" action="js/sendmail.php">
<div class="form-group fl_wrap">
<label class="fl_label" for="name">Nom :</label>
<input type="text" name="name" value="" id="name" class="form-control fl_input" required>
</div>
<div class="form-group fl_wrap">
<label class="fl_label" for="email">Email :</label>
<input type="text" name="email" value="" id="email" class="form-control fl_input" required>
</div>
<span class="form-group fl_wrap honeypot">
<label class="fl_label" for="last">Honeypot:</label>
<input type="text" name="last" value="" id="last" class="form-control fl_input">
</span>
<div class="form-group fl_wrap">
<label class="fl_label" for="message">Message :</label>
<textarea type="text" name="message" value="" id="message" class="materialize-textarea" required></textarea>
</div>
<div class="form-group">
<button type="submit" value="Send" id="submit" class="btn btn-block">Envoyer</button>
</div>
<div id="form-alert" class="form-group">
<div class="result">
<div class="alert"></div>
</div>
</div>
</form>
As some asked. The HTML is on the index page and the sendmail.php is an independent page.
And this is where the success/alert message is supposed to appear :
Form in website
I'm trying to write a contact form with PHP, Ajax and JQuery.
The error is this:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (
but I dont know what I'm doing wrong, because I copied and paste the code of some tutorial.
i´m using foundation6, php and ajax.
I think that the error is for JSON.parse but i don´t know how resolve
This is my code, you can help me? Thanks
contact.php
<form method="post" id="formulario" data-abide novalidate action="<?php echo get_stylesheet_directory_uri(); ?>/src/assets/php/enviar.php">
<div class="campo">
<label for="nombre">Nombre:
<input type="text" id="nombre" placeholeder="Nombre" name="name" required>
<span class="form-error">Error el nombre no puede ir vacio.</span>
</label>
</div>
<div class="campo">
<label for="email">Email:
<input type="text" id="email" placeholeder="Email" name="email" required pattern="email">
<span class="form-error">Error correo vacio o invalido.</span>
</label>
</div>
<div class="campo">
<label for="fecha">Mensaje:
<textarea name="mensaje" rows="6" required></textarea>
<span class="form-error">Error correo vacio o invalido.</span>
</label>
</div>
<div class="campo">
<input type="submit" name="enviar" value="Enviar" class="button explorar">
</div>
</form>
enviar.php
<?php
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
if(is_ajax()) {
$nombre = $_POST['nombre'];
$email = $_POST['email'];
$mensaje = $_POST['mensaje'];
$header = 'From: ' . $email . "\r\n";
$header .= "X-Mailer: PHP/" . phpversion() . "\r\n";
$header .= "Mime-Version: 1.0 \r\n";
$header .= "Content-Type: text/html";
$mensajeCorreo = 'This message was sent by: ' . $nombre . "\r\n";
$mensajeCorreo .= "Email: " . $email . "\r\n";
$mensajeCorreo .= "Mensaje: " . $mensaje . "\r\n";
$para = "email";
$asunto = "Contacto de sitio web";
mail($para, $asunto, utf8_encode($mensajeCorreo), $header );
echo json_encode(array(
'mensaje' => sprintf('El mensaje se ha enviado!')
));
} else {
die("Prohibido!");
}
app.js
// Form Contact
$('#formulario')
.on("invalid.zf.abide", function(ev,elem) {
swal(
'Error!',
'El formulario se envio incompleto',
'error'
);
})
// form validation passed, form will submit if submit event not returned false
.on("formvalid.zf.abide", function(ev,frm) {
var formulario = $(this);
$.ajax({
type: formulario.attr('method'),
url: formulario.attr('action'),
data: formulario.serialize(),
success: function(data) {
var resultado = data;
var respuesta = JSON.parse(resultado);
console.log(respuesta);
swal(
respuesta.message,
'Thank You, ' + respuesta.name + ' for your reservation!',
'success'
)
}
});
})
// to prevent form from submitting upon successful validation
.on("submit", function(ev) {
ev.preventDefault();
console.log("Submit for form id "+ev.target.id+" intercepted");
});
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
I'm trying to make a form that mails the information to me. Here's my code.
PHP:
$to = "mosescu_b#yahoo.com";
$subject = "Comanda de Magneti";
$name = $_POST["nume"] . $_POST["prenume"];
$email = $_POST["email"];
$phone = $_POST["telefon"];
$adress = $_POST["adresa"];
$message = <<<EMAIL
Comanda de Magneti de la $name
Adresa de E-mail este $email
Numarul de telefon este $phone
Adresa este $adress
EMAIL;
$header ="$email";
if($_POST){
mail($to, $subject, $message, $header);
$feedback = "Multumesc pentru comanda!"
}
HTML
<div class="form-group">
<form style="font-size: 1.25em; margin-left: 20px;" method="post" action="#">
<label for="nume">Nume<span style="color: red;">*</span></label> <input name="nume" id="nume" class="form-control" type="text" placeholder="Nume" title="nume">
<label for="prenume">Prenume<span style="color: red;">*</span></label> <input name="prenume" id="prenume" class="form-control" type="text" placeholder="Prenume" title="prenume">
<label for="email">E-Mail</label><span style="color: red;">*</span><input name="email" id="email" class="form-control" type="email" placeholder="E-Mail" title="email">
<label for="telefon">Numar Telefon</label><input name="telefon" id="telefon" class="form-control" type="number" placeholder="Numar Telefon" title="telefon">
<label for="adresa">Adresa</label><span style="color: red;">*</span><input name="adresa" id="adresa" class="form-control" type="text" placeholder="Strada/Numar/Localitate/Judet" title="adresa"> <br />
<input name="submit" class="btn-default" type="submit" value="Comanda!"></input>
</form>
<p id="feedback"><?php echo $feedback ?> </p>
</div>
The error I'm getting is :"Parse error: syntax error, unexpected '}' in C:\wamp64\www\Test\comanda-magneti.php on line 30"
Which is weird, since I'm very sure that the code wouldn't run properly without the curly bracket.
Change this:
$feedback = "Multumesc pentru comanda!"
to
$feedback = "Multumesc pentru comanda!";
You forgot to add semi colon. Semicolon is act is line terminator in PHP and of course you can skip it for last line. But in this case you have closing curly braces after that.
Also please move if($_POST) to top as you are checking for it below and accessing POST properties above.
So something like:
if(isset($_POST)){
$to = "mosescu_b#yahoo.com";
$subject = "Comanda de Magneti";
$name = (isset($_POST["nume"]) ? $_POST["nume"] : '') . isset($_POST["prenume"]) ? $_POST["prenume"] : '' ;
$email = isset($_POST["email"]) ? $_POST["email"];
$phone = isset($_POST["telefon"]) ? $_POST["telefon"] : '';
$adress = isset($_POST["adresa"]) ? $_POST["adresa"] : '';
$message = <<<EMAIL
Comanda de Magneti de la $name
Adresa de E-mail este $email
Numarul de telefon este $phone
Adresa este $adress
EMAIL;
$header ="$email";
mail($to, $subject, $message, $header);
$feedback = "Multumesc pentru comanda!"
}
Also if possible do necessary check for POST variable for required fields.
I am new to PHP, and I made this PHP Mail, for a regular contact form... When the form is completed, the page is redirected and displays "The message was sent succesfully". The problem is, i don't want the page to redirect.. I want to show a feedback on the index, something like a success modal box or a simple text underneath the form "your message was sent"...
Any ideas on how to do this?
<?php
$nome = $_POST['nome'];
$email = $_POST['email'];
$emaildestino = 'contato#zerodesign.com.br';
$email_from='contato#zerodesign.com.br';
$mensagem = $_POST['mensagem'];
$assunto = $_POST['assunto'];
$telefone = $_POST['telefone'];
$titulo = 'Mensagem - TESTE';
<?php
$nome = $_POST['nome'];
$email = $_POST['email'];
$emaildestino = 'contato#zerodesign.com.br';
$email_from='contato#zerodesign.com.br';
$mensagem = $_POST['mensagem'];
$assunto = $_POST['assunto'];
$telefone = $_POST['telefone'];
$titulo = 'Mensagem - TESTE';
$juntando = '<p>Esta mensagem foi enviada pelo site</p><br/>
<p><b>Nome:</b> '.$nome.'</b></p><br>
<p><b>Email:</b> '.$email.' </b></p><br>
<p><b>Telefone:</b> '.$telefone.'</p> </br>
<p><b>Mensagem:</b></p>
<p><i>'.$mensagem.'</i></p>
<hr>';
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\n";
$headers .= "From: $email_from " . "\n";
$envio = mail($emaildestino, $titulo, $juntando, $headers, "-r".$email_from);
if($envio)
echo "Mensagem enviada com sucesso";
else
echo "A mensagem nãpode ser enviada";
?>
Here is my form:
<form method="POST" name="contactform" action="envia.php">
<p><input id="inputt" type="text" name="nome" placeholder="Nome" id="nome" ></p>
<p><input id="inputt" type="text" name="email" placeholder="Email" id="email"></p>
<p><input class="inputt" type="text" name="telefone" placeholder="Telefone" id="telefone"> </p>
<p><textarea id="mensagem" name="mensagem" rows="5" cols="40" placeholder="Mensagem" id="mensagem"></textarea></p>
<input id="button" type="submit" value="Enviar"><br>
</form>
If i understand correctly, what you want to do is not visit the envia.php page, you'll need to send an AJAX call there instead. When the ajax call finishes, you can use javascript to update your index page with the success message.
I believe you are looking for something like:
PHP script added to the top of the form page redirecting to the same page
if(isset($_POST['nome'], $_POST['email'], $_POST['mensagem'], $_POST['assunto'], $_POST['telefone']){
...
$envio = mail($emaildestino, $titulo, $juntando, $headers, "-r".$email_from);
if($envio){
$msg = "Mensagem enviada com sucesso";
}else{
$msg = "A mensagem nãpode ser enviada";
}
}
HTML:
<form method="POST" name="contactform" action="<?php echo $_SERVER['SCRIPT_NAME'];?>">
<p><input id="inputt" type="text" name="nome" placeholder="Nome" id="nome" ></p>
<p><input id="inputt" type="text" name="email" placeholder="Email" id="email"></p>
<p><input class="inputt" type="text" name="telefone" placeholder="Telefone" id="telefone"> </p>
<p><textarea id="mensagem" name="mensagem" rows="5" cols="40" placeholder="Mensagem" id="mensagem"></textarea></p>
<input id="button" type="submit" value="Enviar"><br>
<span id="msg"><?php if(isset($msg)){echo $msg;}?></span>
</form>
looking at your site you might want to add the <?php if(isset($msg)){echo $msg;}?> to the top of the page or add a js script that scrolls to the bottom of the page
Just make the action attribute empty like...
<form method="POST" name="contactform" action="">
So, the page will submit to itself.
Purpose of my code is:
- Validate the form and check for empty fields
- Send e-mail to admin
- Add data to Mysql database
- Show data on result.php
Currently im experiencing problems with showing my data on result.php
quiz.php
<?php
require_once("php/db.php"); /* Database Class */
require_once('php/utils/is_email.php'); /* Email Validation Script */
$contact = new Contact();
/* Class Contact */
class Contact
{
private $db; /* the database obj */
//we have to init $errors array, as otherwise form will produce errors on missing array entry
private $errors = array( /* holds error messages */
'aanhef' => '',
'contactpersoon' => '',
'bedrijfsnaam' => '',
'email' => '',
'telefoon' => '',
'vraag1_antwoorden' => '',
'vraag2_antwoorden' => ''
);
private $has_errors; /* number of errors in submitted form */
public function __construct()
{
$this->db = new DB();
if (!empty($_POST['newcontact'])) {
$this->processNewMessage();
}
}
public function processNewMessage()
{
$aanhef = $_POST['aanhef'];
$contactpersoon = $_POST['contactpersoon'];
$bedrijfsnaam = $_POST['bedrijfsnaam'];
$telefoon = $_POST['telefoon'];
$email = $_POST['email'];
$vraag1_antwoorden = $_POST['vraag1_antwoorden'];
$vraag2_antwoorden = $_POST['vraag2_antwoorden'];
/* Server Side Data Validation */
if (empty($aanhef)) {
$this->setError('aanhef', 'Vul uw aanhef in');
}
if (empty($contactpersoon)) {
$this->setError('contactpersoon', 'Vul uw contactpersoon in');
}
if (empty($bedrijfsnaam)) {
$this->setError('bedrijfsnaam', 'Vul uw bedrijfsnaam in');
}
if (empty($telefoon)) {
$this->setError('telefoon', 'Vul uw telefoon in');
}
if (empty($vraag1_antwoorden)) {
$this->setError('vraag1_antwoorden', 'Selecteer een antwoord a.u.b.');
}
if (empty($vraag2_antwoorden)) {
$this->setError('vraag2_antwoorden', 'Selecteer een antwoord a.u.b.');
}
if (empty($email)) {
$this->setError('email', 'Vul uw e-mail in');
}
/* No errors, insert in db
else*/
if(!$this->has_errors) {
if(($ret = $this->db->dbNewMessage($aanhef, $contactpersoon, $bedrijfsnaam, $email, $telefoon, $vraag1_antwoorden, $vraag2_antwoorden)) > '') {
//$json = array('result' => 1);
if (SEND_EMAIL) {
$this->sendEmail($aanhef,$contactpersoon,$bedrijfsnaam,$email,$telefoon,$vraag1_antwoorden,$vraag2_antwoorden);
//This is for relocating to successful result page
header('Location: result.php');
exit;
} else {
//This will need special treatment. You have to prepare an errorpage
//for database-related issues.
header("Location: database-error.html");
exit;
}
}
}
}
public function sendEmail($aanhef,$contactpersoon,$bedrijfsnaam,$email,$telefoon,$vraag1_antwoorden,$vraag2_antwoorden)
{
/* Just format the email text the way you want ... */
$message_body = "<div style=\"font-size:12px; font-weight:normal;\">Hallo,<br><br>"
."Het volgende bedrijf heeft zich zojuist aangemeld voor de Veiligheids Quiz:</div><br>"
."<table cellpadding=\"1\" cellspacing=\"1\" width=\"550px\"><tr><td style=\"font-size:12px; color:#000000\">Bedrijfsnaam:</td><td style=\"font-size:12px; color:#000000\">".$bedrijfsnaam."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Aanhef:</td><td style=\"font-size:12px; color:#000000\">".$aanhef."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Contactpersoon:</td><td style=\"font-size:12px; color:#000000\">".$contactpersoon."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Telefoonnummer:</td><td style=\"font-size:12px; color:#000000\">".$telefoon."</td></tr><tr><td style=\"font-size:12px; color:#000000\">E-mail:</td><td style=\"font-size:12px; color:#000000\">".$email."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Antwoord vraag 1:</td><td style=\"font-size:12px; color:#000000\">".$vraag1_antwoorden."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Antwoord vraag 2:</td><td style=\"font-size:12px; color:#000000\">".$vraag2_antwoorden."</td></tr></table><br>";
// Geef GELDIGE adressen op
// Een korte benaming voor jouw website
$website_naam = 'Aanmelding Quiz';
// Jouw eigen geldige emailadres
$eigen_emailadres = 'MY MAIL';
// Een geldig emailadres voor errors
$error_emailadres = 'MY MAIL';
// De naam van de verzender
$naam_verzender = ''.$bedrijfsnaam.'';
// Het geldige emailadres van de afzender
$email_verzender = ''.$email.'';
// Een geldig emailadres of helemaal leeg laten
$bcc_emailadres = '';
// HTML mail? True/False
$html = true;
// De headers samenstellen
$headers = 'From: ' . $website_naam . ' <' . $eigen_emailadres . '>' . PHP_EOL;
$headers .= 'Reply-To: ' . $naam_verzender . ' <' . $email_verzender . '>' . PHP_EOL;
$headers .= 'Return-Path: Mail-Error <' . $error_emailadres . '>' . PHP_EOL;
$headers .= ($bcc_emailadres != '') ? 'Bcc: ' . $bcc_emailadres . PHP_EOL : '';
$headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
$headers .= 'X-Priority: Normal' . PHP_EOL;
$headers .= ($html) ? 'MIME-Version: 1.0' . PHP_EOL : '';
$headers .= ($html) ? 'Content-type: text/html; charset=iso-8859-1' . PHP_EOL : '';
mail(EMAIL_TO,MESSAGE_SUBJECT,$message_body,$headers);
}
public function setError($field, $errmsg)
{
$this->has_errors = true;
$this->errors[$field] = $errmsg;
}
public function errors($field)
{
if (array_key_exists($field,$this->errors)){
return $this->errors[$field];
}
return '';
}
};
?>
<table width="675px" cellpadding="0" cellspacing="0">
<form id="contact_form" method="post" action="">
<label class="label_aanhef" for="aanhef_1"><input name="aanhef" id="aanhef_1" type="radio" value="Dhr." /> Dhr.</label><label class="label_aanhef" for="aanhef_2"><input name="aanhef" id="aanhef_2" type="radio" value="Mevr." /> Mevr.</label>
<span class="error"><?php echo $contact->errors('aanhef'); ?></span>
<input id="contactpersoon" name="contactpersoon" maxlength="120" type="text" onFocus="window.scrollTo(0, 0);"/><span class="error"><?php echo $contact->errors('contactpersoon'); ?></span>
<input id="bedrijfsnaam" name="bedrijfsnaam" maxlength="120" type="text" onFocus="window.scrollTo(0, 0);"/><span class="error"><?php echo $contact->errors('bedrijfsnaam'); ?></span>
<input id="email" name="email" maxlength="120" type="text" onFocus="window.scrollTo(0, 0);"/><span class="error"><?php echo $contact->errors('email'); ?></span>
<input id="telefoon" name="telefoon" maxlength="120" type="text" onFocus="window.scrollTo(0, 0);"/><span class="error"><?php echo $contact->errors('telefoon'); ?></span>
<label class="label_radio" for="vraag1_A"><input name="vraag1_antwoorden" id="vraag1_A" value="A. Dat is helaas fout, het goede antwoord is: C) < 1 Ohm" type="radio" />A) Geen eis</label>
<label class="label_radio" for="vraag1_B"><input name="vraag1_antwoorden" id="vraag1_B" value="B. Dat is helaas fout, het goede antwoord is: C) < 1 Ohm" type="radio" />B) < 0,1 Ohm</label>
<label class="label_radio" for="vraag1_C"><input name="vraag1_antwoorden" id="vraag1_C" value="C. Gefeliciteerd dat is het goede antwoord." type="radio" />C) < 1 Ohm</label>
<label class="label_radio" for="vraag1_D"><input name="vraag1_antwoorden" id="vraag1_D" value="D. Dat is helaas fout, het goede antwoord is: C) < 1 Ohm" type="radio" />D) < 10 Ohm</label>
<span id="vraag1_antwoorden" class="foutmelding_quiz">
<?php echo $contact->errors('vraag1_antwoorden'); ?>
</span>
<label class="label_radio" for="vraag2_A"><input name="vraag2_antwoorden" id="vraag2_A" value="A. Gefeliciteerd dat is het goede antwoord." type="radio" />A) Geen eis</label>
<label class="label_radio" for="vraag2_B"><input name="vraag2_antwoorden" id="vraag2_B" value="B. Dat is helaas fout, het goede antwoord is: A) Geen eis" type="radio" />B) < 0,1 Ohm</label>
<label class="label_radio" for="vraag2_C"><input name="vraag2_antwoorden" id="vraag2_C" value="C. Dat is helaas fout, het goede antwoord is: A) Geen eis" type="radio" />C) < 1 Ohm</label>
<label class="label_radio" for="vraag2_D"><input name="vraag2_antwoorden" id="vraag2_D" value="D. Dat is helaas fout, het goede antwoord is: A) Geen eis" type="radio" />D) < 10 Ohm</label>
<span id="vraag2_antwoorden" class="foutmelding_quiz">
<?php echo $contact->errors('vraag2_antwoorden'); ?>
</span>
<input class="button submit" type="submit" value="" /><input id="newcontact" name="newcontact" type="hidden" value="1"></input>
</form>
Result.php
Aanhef: <?php echo $_POST["aanhef"]; ?><br />
Contactpersoon: <?php echo $_POST["contactpersoon"]; ?><br />
Bedrijfsnaam: <?php echo $_POST["bedrijfsnaam"]; ?><br />
Telefoon: <?php echo $_POST["telefoon"]; ?><br />
E-mail: <?php echo $_POST["email"]; ?><br />
if(!empty($_POST['newcontact'])){
$contact = new Contact();
} else{
//header('Location: result.php');
}
Change it to
$contact = new Contact();
I mean to say : remove condition if() :
Its b'coz when page is not posted it will not create object of class Contact.
Due to this error comes.
You should replace :
if(!empty($_POST['newcontact'])){
$contact = new Contact();
} else{
//header('Location: result.php');
}
By :
$contact = new Contact();
Cause if $_POST['newcontact'] is empty, your $contact object is not set, and the if(!empty($_POST['newcontact'])) is already in your __construct() of Contact
Add something like this to Contact to replace your redirect :
private $display_form = true;
public function getDisplayForm() {
return $this->display_form;
}
And replace :
header('Location: result.php');
exit;
By :
$this->display_form = false;
And below, wrap your HTML like this :
<?php if ($contact->getDisplayForm()) { ?>
<!-- Your Form -->
<table width="675px" cellpadding="0" cellspacing="0">
<form id="contact_form" method="post" action="">
...
</form>
</table>
<?php } else { ?>
<!-- Your Results -->
Aanhef: <?php echo $_POST["aanhef"]; ?><br />
Contactpersoon: <?php echo $_POST["contactpersoon"]; ?><br />
Bedrijfsnaam: <?php echo $_POST["bedrijfsnaam"]; ?><br />
Telefoon: <?php echo $_POST["telefoon"]; ?><br />
E-mail: <?php echo $_POST["email"]; ?><br />
<?php } ?>
Are you sure that $contacts is actually filled?
I see this statement at the beginning of the page:
if(!empty($_POST['newcontact'])){
$contact = new Contact();
} else{
//header('Location: result.php');
}
But no further checks if contacts is actually set. If the POST was empty contacts will be null. Check if contacts is null, and if it is, don't call methods or variables on it. :-)