I'm making an app with ionic 2 angular 2, and I have made a mailform in php. Now how can I make my app use my php file to send the mailform?
this is my html
<ion-header>
<ion-navbar>
<ion-title>Mail</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<form id="mailform" action="mailform.php" method="post">
<ion-item>
<ion-input type="text" id="naam" placeholder="Naam" required="required" pattern="\D*"></ion-input>
</ion-item>
<ion-item>
<ion-input type="text" id="voornaam" placeholder="Voornaam" required="required" pattern="\D*"></ion-input>
</ion-item>
<ion-item>
<ion-input type="text" id="email" placeholder="Email" required="required" pattern="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"> </ion-input>
</ion-item>
<ion-item>
<ion-select placeholder="Onderwerp" required="required">
<ion-option id="Bug">Bug</ion-option>
<ion-option id="FouteInfo">Foute info</ion-option>
</ion-select>
</ion-item>
<ion-item>
<textarea id="text" id="text" type="text" rows="5" placeholder="Vertel ons het probleem" required="required"></textarea>
</ion-item>
<a (click)="send()" ion-button color="primary" icon-left>
<ion-icon name="at" (click)="send"></ion-icon>
Verstuur
</a>
</form>
</ion-list>
</ion-content>
this is my php file
<ion-header>
<ion-navbar>
<ion-title>Mail</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<?php
$ok = false;
if (preg_match("/\D*/", $_POST["naam"])){
$naam = true;
}
else {
echo "Naam niet goed <br/>";
}
if (preg_match("/\D*/", $_POST["voornaam"])){
$voornaam = true;
}
else {
echo "Voornaam niet goed <br/>";
}
if(isset($_POST['bug'])){
$bug = true;
}
else {
$bug = false;
}
if(isset($_POST['fouteInfo'])){
$fouteInfo = true;
}
else {
$fouteInfo = false;
}
if (preg_match("/^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/", $_POST["email"])){
$email = true;
}
else {
echo "email adres niet correct <br/>"
}
if (!empty($_POST["text"])){
$text = true;
}
else {
echo "text invullen aub <br/>";
}
if ($naam && $voornaam && $email && $text && ($bug || $fouteInfo)) {
$ok = true;
}
//Bericht voor admin
$to = "anthony.gesquiere#student.vives.be";
//$to = $_POST['email'];
if($bug){
$subject = "Bug";
}
else {
$subject = "Foute Info";
}
$message = "Naam: " . $_POST['naam'] . $_POST['voornaam'] . "<br/> Email: " . $_POST['email'] . "<br /> Bericht: " . $_POST['text'];
$header = "From: Stad Kortrijk <noreply#kortrijk.be> \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retvalAdmin = mail($to,$subject,$message,$header);
//Bericht voor gebruiker
$to = $_POST['email'];
$subject = "Bedankt voor uw melding";
$message ="<h1>Bedankt ". $_POST['naam'] . " " . $_POST['voornaam'] . " </h1> <br/><br> We zullen dit probleem zo spoedig mogelijk trachten op te lossen <br>Met vriendelijke groeten <br> Stad Kortrijk <br/>";
$header = "From: Stad Kortrijk <noreply#kortrijk.be> \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail($to,$subject,$message,$header);
if( $retval == true )
{
echo "Bedankt voor uw aanvraag";
}
else
{
echo "Er is een fout opgetreden, uw aanvraag werd niet verstuurd, excuses voor dit ongemak. ";
}
}
else {
var_dump($_POST);
}
?>
</ion-content>
Now how do I make this work so that my app sends a http post request to my server where my php file is running, so that it sends the mailform?
Related
My PHP email form code is working though, but the output after submitting the message is not correct.
After sending a message it is poping an “OK” echo on a blank page (URL www.domain.com/mailform.php), instead of fading out the contact form on the page and fading in the “successful sent” message, without changing the URL.
Where is the bug in the code? :(
HTML
<div class="contact-form-grid">
<form method="post" name="contactForm" id="contactForm" action="sendEmail.php">
<div class="fields-grid">
<div class="styled-input agile-styled-input-top">
<input type="text" for="contactName" id="contactName" name="contactName" required="" />
<label>Dein Name</label></div>
<div class="styled-input agile-styled-input-top">
<input type="text" for="contactTel" name="contactTel" required="" />
<label>Telefon</label></div>
<div class="styled-input">
<input type="email" for="contactEmail" id="contactEmail" name="contactEmail" required="" />
<label>E-Mail</label></div>
<div class="styled-input">
<input type="text" for="contactSubject" id="contactSubject" name="contactSubject" required="" />
<label>Betreff</label></div>
<div class="clearfix"></div>
</div>
<div class="styled-input textarea-grid">
<textarea name="contactMessage" required=""></textarea>
<label>Schreibe hier deine Nachricht!</label></div>
<input type="submit" value="Senden" />
<div id="submit-loader">
<div class="text-loader">Senden...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</form>
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">Ihre Nachricht wurde abgeschickt, danke!
<br /></div>
</div>
PHP
<?php
// Replace this with your own email address
$siteOwnersEmail = 'myemail#gmail.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$tel = trim(stripslashes($_POST['contactTel']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Bitte geben Sie Ihren Namen ein.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Bitte geben Sie eine korrekte E-Mail-Adresse ein.";
}
// Subject
if ($subject == '') { $subject = "Anfrage"; }
// Set Message
$message .= "<strong>" . "Absender: " . "</strong>". $name . "<br />";
$message .= "<strong>" . "Email: " . "</strong>" . $email . "<br /><br />";
$message .= "<strong>" . "Telefon: " . "</strong>" . $tel . "<br /><br />";
$message .= "Nachricht: <br />";
$message .= $contact_message . "<br />";
$message .= "<br /> ----- <br /><i> Gesendet von .... </i></font><br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8";
if (!$error) {
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Etwas ging schief! Probiere später nochmal."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
JS
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Etwas ging schief! Probiere später nochmal.");
$('#message-warning').fadeIn();
}
});
}
});
I hope someone can help me here :(
Your error is probably in your javascript, is the page refreshing before saying "OK"?
A simpler way to submit a form with ajax is:
$("#form").ajaxForm({
url: "",
beforeSubmit: function() {
},
success: function() {
},
error: function() {
}
});
Did you try this?
I am using bootstrap and have a form I've been using for a while now. It shows the message "Verzonden!" on the same page if the form has been submitted succesfully. now this has to be altered to redirect to a new succes page after the form is submitted.
this is the html I am using
<form role="form" id="contactForm" class="contact-form" data-toggle="validator" class="shake">
<div class="form-group">
<div class="controls">
<input type="text" id="name" class="form-control" placeholder="Naam & Voornaam" required data-error="Gelieve uw naam in te vullen.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" class="email form-control" id="email" placeholder="Email" required data-error="Gelieve uw email adres in te vullen.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" id="phone" class="form-control" placeholder="Telefoonnummer" required data-error="Gelieve uw telefoonnummer in te vullen.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" id="msg_subject" class="form-control" placeholder="Onderwerp" required data-error="Gelieve een onderwerp in te vullen.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<textarea id="message" rows="7" placeholder="Bericht" class="form-control" required data-error="Gelieve uw bericht in te vullen."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<button type="submit" id="submit" class="btn btn-success"></i>Verzend!</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
This is the php I am using:
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Gelieve uw naam in te vullen.";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Gelieve uw email adres in te vullen.";
} else {
$email = $_POST["email"];
}
// PHONE
if (empty($_POST["phone"])) {
$errorMSG .= "Gelieve uw telefoonnummer in te vullen.";
} else {
$phone = $_POST["phone"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Gelieve een onderwerp in te vullen.";
} else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Gelieve een bericht in te vullen";
} else {
$message = $_POST["message"];
}
//Add your email here
$EmailTo = "e-mail address";
$Subject = "Nieuw bericht van website";
// prepare email body text
$Body = "";
$Body .= "Naam: ";
$Body .= "\n";
$Body .= $name;
$Body .= "\n";
$Body .= "\n";
$Body .= "Email: ";
$Body .= "\n";
$Body .= $email;
$Body .= "\n";
$Body .= "\n";
$Body .= "Telefoonnummer: ";
$Body .= "\n";
$Body .= $phone;
$Body .= "\n";
$Body .= "\n";
$Body .= "Onderwerp: ";
$Body .= "\n";
$Body .= $msg_subject;
$Body .= "\n";
$Body .= "\n";
$Body .= "Bericht: ";
$Body .= "\n";
$Body .= $message;
$Body .= "\n";
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "Verzonden!";
}else{
if($errorMSG == ""){
echo "Er is een fout opgetreden, probeert u aub opnieuw.";
} else {
echo $errorMSG;
}
}
?>
You have to redirect the user to a new page using the php header function:
// redirect to success page
if ($success && $errorMSG == ""){
header('Location: http://www.example.com/success-page.php');
}else{
if($errorMSG == ""){
echo "Er is een fout opgetreden, probeert u aub opnieuw.";
} else {
echo $errorMSG;
}
}
IMPORTANT NOTE
Never print or echo anything before the header() redirect call or else it will not redirect the user.
Read the reference here:
http://php.net/manual/en/function.header.php
UPDATE
// redirect to success page
if ($success && $errorMSG == ""){
header('Location: http://www.example.com/success-page.php');
}else{
if($errorMSG == ""){
header('Location: http://www.example.com/success-page.php');
} else {
echo $errorMSG;
}
}
also added condition for if($errorMSG == "")
Also
It is a good practice to add the action attribute in your form like so:
<form action="path-to-your-processing-script.php">
If you don't provide that it will submit the form on the same page but still you should give it anyway.
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!
I'm quite new to PHP and I needed a contact form so I took one off the internet and edited everything I needed/wanted too. The mail won't send though, so if anyone could help me fix this I would be very happy!
HTML:
<form name="contactform" method="post"action="send_form_email.php">
<p class="name">
<input type="text" name="first_name" id="name" placeholder="Fullständigt namn" />
</p>
<p class="foretag">
<input type="text" name="foretag" id="foretag" placeholder="Företag" />
</p>
<p class="email">
<input type="text" name="email" id="email" placeholder="Email" />
</p>
<p class="telefon">
<input type="text" name="telephone" id="telephone" placeholder="Telefonnummer" />
</p>
<p class="text">
<textarea name="text" id="text" placeholder="Meddelande" /></textarea>
</p>
<p class="robotic" id="pot">
<label>Om du är människa, fyll inte i denna ruta:</label>
<input name="robotest" type="text" id="robotest" class="robotest" />
</p>
<p class="submit">
<input type="submit" value="Skicka" />
</p>
</form>
</div>
PHP:
<?php
if(isset($_POST['email'])) {
$email_to = "EMAIL HERE";
$email_subject ="subject";
function died($error) {
// your error code can go here
echo "Fel uppstog";
echo "Error kod:.<br /><br />";
echo $error."<br /><br />";
echo "Gå tillbaka och rätta till problemen innan du försöker igen.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['foretag']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['text'])) {
died('Det verkar vara ett problem med formuläret du angav');
}
$first_name = $_POST['first_name'];
$foretag = $_POST['foretag'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$text = $_POST['text'];
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$error_message .= 'Emailadressen du angav verkar inte vara giltig.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'Namnet du angav verkar inte vara giltig.<br />';
}
if(!preg_match($string_exp,$foretag)) {
$error_message .= 'Företaget du angav är inte giltig..<br />';
}
if(strlen($text) < 2) {
$error_message .= 'Meddelandet du angav är inte giltig..<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
if (preg_match("/http/i", "$first_name")) {echo "$spamErrorMessage"; exit();}
if (preg_match("/http/i", "$email")) {echo "$spamErrorMessage"; exit();}
if (preg_match("/http/i", "$telephone")) {echo "$spamErrorMessage";exit();}
if (preg_match("/http/i", "$text")) {echo "$spamErrorMessage"; exit();}
$SpamErrorMessage = "Ingen URL tillåten";
$headers = 'From: '.$email_from."\r\n";
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
if($robotest)
$error = "You are a gutless robot.";
else {
#mail($email_to, $email_subject, $email_message, $headers);
}
}
?>
<input type="text" name="name" id="name" placeholder="Fullständigt namn" />
should be
<input type="text" name="first_name" id="name" placeholder="Fullständigt namn" />
I had to modify a few things in your form and PHP handler in order to get all the fields to match and work.
NOTE: You will need to modify a few things in your own language, but besides that, this worked for me and Email was in fact sent and received.
HTML form
<form name="contactform" method="post" action="send_form_email.php">
<p class="name">
<input type="text" name="first_name" id="first_name" placeholder="Fullständigt namn" />
</p>
<p class="last_name">
<input type="text" name="last_name" id="last_name" placeholder="Last name" />
</p>
<p class="foretag">
<input type="text" name="foretag" id="foretag" placeholder="Företag" />
</p>
<p class="email">
<input type="text" name="email_from" id="email" placeholder="Email" />
</p>
<p class="telefon">
<input type="text" name="telephone" id="telephone" placeholder="Telefonnummer" />
</p>
<p class="text">
<textarea name="text" id="text" placeholder="Meddelande" /></textarea>
</p>
<p class="robotic" id="pot">
<label>Om du är människa, full inte i denna ruta:</label>
<input name="robotest" type="text" id="robotest" class="robotest" />
</p>
<p class="submit">
<input type="submit" value="Skicka" />
</p>
</form>
</div>
PHP handler (send_form_email.php)
<?php
if(isset($_POST['email_from'])) {
$email_to = "email#example.com";
$email_subject = "bezod-design kontakta";
// } this could be used, didn't make much of a difference.
// closing brace for this is commented at the end of this code
// but you will need to delete the closing brace at the end if using the closing brace here
function died($error) {
// your error code can go here
echo "Erros uppstog";
echo "Dem/det är listade nedan.<br /><br />";
echo $error."<br /><br />";
echo "Gå tillbaks och fix dem innan du skickar.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['foretag']) ||
!isset($_POST['email_from']) ||
!isset($_POST['telephone']) ||
!isset($_POST['text'])) {
died('Det värkar vara ett problem med formuläret du skrev');
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$foretag = $_POST['foretag'];
$email_from = $_POST['email_from'];
$telephone = $_POST['telephone'];
$text = $_POST['text'];
$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 .= 'Email adressen du skrev värkar inte vara giltig.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'Namnet adressen du skrev värkar inte vara giltig.<br />';
}
if(!preg_match($string_exp,$foretag)) {
$error_message .= 'Företaget du skrev värkar inte vara giltig..<br />';
}
if(strlen($text) < 2) {
$error_message .= 'Meddelandet du skrev värkar inte vara giltig..<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Foretag: ".clean_string($foretag)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($text)."\n";
if (preg_match("/http/i", "$first_name")) {echo "$spamErrorMessage"; exit();}
if (preg_match("/http/i", "$email_from")) {echo "$spamErrorMessage"; exit();}
if (preg_match("/http/i", "$telephone")) {echo "$spamErrorMessage";exit();}
if (preg_match("/http/i", "$text")) {echo "$spamErrorMessage"; exit();}
$SpamErrorMessage = "Ingen URL tillåten";
$headers = 'From: '.$email_from."\r\n";
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
if($robotest)
$error = "You are a gutless robot.";
else {
mail($email_to, $email_subject, $email_message, $headers);
echo "Message sent.";
}
} // closing brace for if(isset at beginning of handler
// delete this brace if you are to use the closing one at the beginning
?>
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. :-)