I got a simple email form that sends mails correctly except there is no data inside them. It also sends emails twice. What could be the cause of this?
contact.php :
<form class="contact-form columns_padding_5" method="post" action="mail/mail-send.php">
<div class="col-sm-6">
<p class="contact-form-name">
<label for="name">Naam<span class="required">*</span></label>
<input type="text" aria-required="true" size="30" value="" name="name" id="name" class="form-control" placeholder="Naam">
</p>
</div>
<div class="col-sm-6">
<p class="contact-form-subject">
<label for="subject">Onderwerp<span class="required">*</span></label>
<input type="text" aria-required="true" size="30" value="" name="subject" id="subject" class="form-control" placeholder="Onderwerp">
</p>
</div>
<div class="col-sm-6">
<p class="contact-form-phone">
<label for="email">Email-adres<span class="required">*</span></label>
<input type="email" aria-required="true" size="30" value="" name="email" id="email" class="form-control" placeholder="Email-adres">
</p>
</div>
<div class="col-sm-6">
<p class="contact-form-email">
<label for="phone">Telefoonnummer<span class="required">*</span></label>
<input type="text" aria-required="true" size="30" value="" name="phone" id="phone" class="form-control" placeholder="Telefoonnummer">
</p>
</div>
<div class="col-sm-12">
<p class="contact-form-message">
<label for="message">Bericht</label>
<textarea aria-required="true" rows="6" cols="45" name="message" id="message" class="form-control" placeholder="Bericht"></textarea>
</p>
</div>
<div class="col-sm-12">
<p class="contact-form-submit topmargin_30">
<button type="submit" id="contact_form_submit" name="contact_submit" class="theme_button wide_button color1">Verstuur bericht</button>
<button type="reset" id="contact_form_reset" name="contact_reset" class="theme_button wide_button">Leeg formulier</button>
</p>
</div>
</form>
mail-send.php :
<?PHP
require_once("../phpMailer/class.phpmailer.php");
$isValid = true;
if(isset($_POST['name']) && isset($_POST['subject']) && isset($_POST['email']) && isset($_POST['message']))
{
$name = $_POST['name'];
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];
$phone = $_POST['phone'];
$mail = new PHPMailer;
$mail->From = $email;
$mail->FromName = $name;
$mail->addAddress("email#live.nl"); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$texts = 'Er is een aanvraag op de website van website<br /> <br />
<b>Naam:</b> '.$name.'<br />
<b>E-mail adres:</b> '.$email.'<br />
<b>Onderwerp:</b> '.$subject.'<br />
<b>Telefoonnummer:</b>'.$phone.'<br />
<b>Vragen / Opmerkingen:</b> '.$message.'<br /><br /><br />
';
$handtekening = '
<table border="0" width="100%" cellspacing="0" cellpadding="0" style="font-family:calibri;color: #5C5C5C; font-size:10pt;line-height:22px;">
<tr>
<td width="160" valign="top" style="font-family:calibri;padding-left:10px;padding-top:20px;">
[contents]
</td>
</tr>
<tr>
<td width="160" valign="top" style="font-family:calibri;padding-left:10px;padding-top:20px;">
<br><br>Met vriendelijke groet,<br><br>
Helpdesk<br>
<b>website</b><br>
<p></p>
</td>
</tr>
</table>
<table height="120" border="0" width="100%" cellspacing="0" cellpadding="0" style="font-family:calibri;color: #5C5C5C; font-size:10pt;line-height:22px;">
<tr>
<td width="250" valign="top" style="font-family:calibri;padding-left:10px;padding-top:20px;border-top: 1px #000000 dotted; border-bottom: 1px #000000 dotted;">
E:
info#website.nl<br>
T:
0615086609<br>
W:
www.website.nl<br>
</td>
<td align="right" style="font-family:calibri;padding-right:10px;padding-top:5px;border-top: 1px #000000 dotted; border-bottom: 1px #000000 dotted;">
<a href="http://website.nl/" target="_blank" title="Ga naar de website">
<img src="http://website.nl/_extern/website/images/logo/logo.png" alt="Ga naar de website" style="font-family:calibri;text-align:right;margin:0px;padding:10px 0 10px 0;" border="0" width="232">
</a>
</td>
</tr>
<tr>
<td colspan="2" style="font-family:calibri;color:#a3a3a3;font-size:11px;margin-top:6px;line-height:14px;">
<br>Dit e-mailbericht is uitsluitend bestemd voor de geadresseerde. Als dit bericht niet voor u bestemd is, wordt u vriendelijk verzocht dit aan de afzender te melden. website staat door de elektronische verzending van dit bericht niet in voor de juiste en volledige overbrenging van de inhoud, noch voor tijdige ontvangst daarvan. Voor informatie over website raadpleegt u website.<br><br>
</td>
</tr>
</table>';
$contents = preg_replace('/\[contents]/',$texts, $handtekening);
$mail->msgHTML($contents);
$mail->AltBody = $texts;
if(!$mail->send())
{
$isValid = false;
}
$mail = new PHPMailer;
$mail->From = 'info#website.nl';
$mail->FromName = 'website';
$mail->addAddress($email); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Bedankt voor uw aanvraag bij website';
$texts = 'Geachte heer/mevrouw '.$naam.',<br /><br />
Hartelijk dank voor uw aanvraag bij website<br />
Wij reageren zo spoedig mogelijk op uw aanvraag.<br /><br />
Uw gegevens worden nooit aan derden ter hand gesteld.
';
$contents = preg_replace('/\[contents]/',$texts, $handtekening);
$mail->msgHTML($contents);
$mail->AltBody = $texts;
if(!$mail->send())
$isValid = false;
}
if($isValid == true) {
$result["submit_message"] = _msg_send_ok;
} else {
$result["submit_message"] = _msg_send_error;
}
if($_POST["name"]=="" || $_POST["name"]==_def_name)
$result["error_name"] = _msg_invalid_data_name;
if($_POST["email"]=="" || $_POST["email"]==_def_email || !preg_match("#^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$#", $_POST["email"]))
$result["error_email"] = _msg_invalid_data_email;
if($_POST["message"]=="" || $_POST["message"]==_def_message)
$result["error_message"] = _msg_invalid_data_message;
$result['isValid'] = $isValid;
echo json_encode($result);
This is the ajax part that processes the contact form:
//function that initiating template plugins on document.ready event
function documentReadyInit() {
///////////
//Plugins//
///////////
//contact form processing
jQuery('form.contact-form').on('submit', function( e ){
e.preventDefault();
var $form = jQuery(this);
jQuery($form).find('span.contact-form-respond').remove();
//checking on empty values
jQuery($form).find('[aria-required="true"], [required]').each(function(index) {
if (!jQuery(this).val().length) {
jQuery(this).addClass('invalid').on('focus', function(){jQuery(this).removeClass('invalid')});
}
});
//if one of form fields is empty - exit
if ($form.find('[aria-required="true"], [required]').hasClass('invalid')) {
return false;
}
//sending form data to PHP server if fields are not empty
var request = $form.serialize();
var ajax = jQuery.post( "mail/mail-send.php", request )
.done(function( data ) {
jQuery($form).find('[type="submit"]').attr('disabled', false).parent().append('<span class="contact-form-respond highlight">'+data+'</span>');
})
.fail(function( data ) {
jQuery($form).find('[type="submit"]').attr('disabled', false).parent().append('<span class="contact-form-respond highlight">Mail cannot be sent. You need PHP server to send mail.</span>');
})
});
And finally my config file where some data is set like the success/failure messages:
config.php :
<?php
define('_from_name', 'website');
define('_from_email', 'info#website.nl');
define('_to_name', '');
define('_to_email', 'website#live.nl');
define('_smtp_host', '');
define('_smtp_username', '');
define('_smtp_password', '');
define('_smtp_port', '');
define('_smtp_secure', ''); //ssl or tls
define('_subject_email', 'website: Contactaanvraag');
define('_def_name', 'Uw Naam *');
define('_def_email', 'Uw Emailadres *');
define('_def_phone', 'Uw Telefoonnummer');
define('_def_message', 'Bericht *');
define('_def_message_appointment', 'Aanvullende informatie');
define('_msg_invalid_data_name', 'Voer een naam in.');
define('_msg_invalid_data_email', 'Voer een geldig emailadres in.');
define('_msg_invalid_data_message', 'Voer een bericht in.');
define('_msg_send_ok', 'Bedankt voor uw bericht!');
define('_msg_send_error', 'Dit bericht kan niet worden verzonden.');
?>
The correct behaviour should be:
One confirmation mail to the mail the customer filled in, and one mail which the customer wrote to the company.
Now I receive two mails (with no data in them) for the company and the customer receives nothing.
Here you can see the mail is sent correctly:
And these are the two success messages I get (in json, I don't know how to decode it)
if(!$mail->send())
{
$isValid = false;
}
$mail = new PHPMailer;
$mail->From = 'info#website.nl';
$mail->FromName = 'website';
$mail->addAddress($email); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Bedankt voor uw aanvraag bij website';
$texts = 'Geachte heer/mevrouw '.$naam.',<br /><br />
Hartelijk dank voor uw aanvraag bij website<br />
Wij reageren zo spoedig mogelijk op uw aanvraag.<br /><br />
Uw gegevens worden nooit aan derden ter hand gesteld.
';
$contents = preg_replace('/\[contents]/',$texts, $handtekening);
$mail->msgHTML($contents);
$mail->AltBody = $texts;
if(!$mail->send())
{
$isValid = false;
}
You're testing if(!$mail->send()) twice.
Related
I am getting the error Failed to load resource: the server responded with a status of 404 (Not Found) and not really sure why it is happening. I have checked the routes and access of the files and everything seems fine.
My Js file looks like this:
var clContactForm = function() {
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('.submit-loader');
$.ajax({
type: "POST",
url: "../inc/sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.slideDown("slow");
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.slideUp("slow");
$('.message-warning').fadeOut();
$('#contactForm').fadeOut();
$('.message-success').fadeIn();
}
// There was an error
else {
sLoader.slideUp("slow");
$('.message-warning').html(msg);
$('.message-warning').slideDown("slow");
}
},
error: function() {
sLoader.slideUp("slow");
$('.message-warning').html("Algo ocurrió. Por favor, inténtalo de nuevo");
$('.message-warning').slideDown("slow");
}
});
}
});
};
My php code looks like this:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'myemail#gmail.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Por favor, coloca tu nombre.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Por favor, pon un correo válido.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Por favor, coloca tu mensaje";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <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=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Oops! Algo ocurrió, por favor inténtalo de nuevo."; }
} # 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
}
?>
And finally, my HTML code is this one:
<div class="row section-header" data-aos="fade-up">
<div class="col-full">
<h1 class="display-2 display-2--light">Cuéntanos un poco más de tí para que empieces a vivir la experiencia Tech Consultant</h1>
</div>
</div>
<div class="row contact-content" data-aos="fade-up">
<div class="contact-primary">
<h3 class="h6">Envíanos un mensaje</h3>
<form name="contactForm" id="contactForm" method="post" action="/index.html" novalidate="novalidate">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Nombre" value="" minlength="2" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Asunto" value="" class="full-width">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="¿Qué es lo que más te interesa de Tech Consultant?" rows="10" cols="50" required="" aria-required="true" class="full-width"></textarea>
</div>
<div class="form-field">
<button class="full-width btn--primary">Enviar</button>
<div class="submit-loader">
<div class="text-loader">Enviando...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</fieldset>
</form>
<!-- contact-warning -->
<div class="message-warning">
¡Algo ocurrió! Por favor, intenta de nuevo.
</div>
<!-- contact-success -->
<div class="message-success">
¡Hemos recibido tu mensaje! Nuestros asesores se pondrán en contacto contigo<br>
</div>
</div> <!-- end contact-primary -->
As I mentioned before, I am getting the Failed to load resource: the server responded with a status of 404 (Not Found) error and I am not really sure why. If you can give me some insight, that would be amazing!
Thank you in advance for all of your help!!
I did some changes to your code
yes that code was not working
i sorted the same on my localhost
Please compare the code:
Updated code: ( Html and js code)
$(document).ready(function () {
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('.submit-loader');
$.ajax({
type: "POST",
url: "process.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.slideDown("slow");
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.slideUp("slow");
$('.message-warning').fadeOut();
$('#contactForm').fadeOut();
$('.message-success').fadeIn();
}
// There was an error
else {
sLoader.slideUp("slow");
$('.message-warning').html(msg);
$('.message-warning').slideDown("slow");
}
},
error: function() {
sLoader.slideUp("slow");
$('.message-warning').html("Algo ocurrió. Por favor, inténtalo de nuevo");
$('.message-warning').slideDown("slow");
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<div class="row section-header" data-aos="fade-up">
<div class="col-full">
<h1 class="display-2 display-2--light">Cuéntanos un poco más de tí para que empieces a vivir la experiencia Tech Consultant</h1>
</div>
</div>
<div class="row contact-content" data-aos="fade-up">
<div class="contact-primary">
<h3 class="h6">Envíanos un mensaje</h3>
<form name="contactForm" id="contactForm" method="post" novalidate="novalidate">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Nombre" value="" minlength="2" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Asunto" value="" class="full-width">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="¿Qué es lo que más te interesa de Tech Consultant?" rows="10" cols="50" required="" aria-required="true" class="full-width"></textarea>
</div>
<div class="form-field">
<button class="full-width btn--primary">Enviar</button>
<div class="submit-loader">
<div class="text-loader">Enviando...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</fieldset>
</form>
<!-- contact-warning -->
<div class="message-warning">
¡Algo ocurrió! Por favor, intenta de nuevo.
</div>
<!-- contact-success -->
<div class="message-success">
¡Hemos recibido tu mensaje! Nuestros asesores se pondrán en contacto contigo<br>
</div>
</div> <!-- end contact-primary -->
**Php Updated code**
<?php
// Replace this with your own email address
$siteOwnersEmail = 'your email id';
if($_POST) {
$message = "";
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
$error = array();
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Por favor, coloca tu nombre.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Por favor, pon un correo válido.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Por favor, coloca tu mensaje";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <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=ISO-8859-1\r\n";
if (!$error) {
//ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Oops! Algo ocurrió, por favor inténtalo de nuevo."; }
} # 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
}
?>
Let me know if you need zip for running code will send you the same:
enter image description here
You may want to try postman to post a form data instead of using a browser. If you do that, you can find out if your PHP code works fine or not, then focus on the JavaScript code.
Today I'm facing another error related with AJAX.
I'm pretending to build a user registration system using ajax and php, with mvc architecture.
I built a login system without ajax and works without any problem, there is connectivity and interaction between all sides.
I'm almost sure that the error comes because of the JS file, I've passed my file through the JSHint to detect errors but nothing found, probably there is some mistake in the logic of the code.
First of all, before to post my code, I'll show you my data files structure to save you some headache thinking about the paths:
I'm going to paste the codes here and then I'll comment something about each piece of code.
View/register.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<link rel="stylesheet" href="../css/register.css">
<script src="../js/valReg.js"></script>
<section class="registerPage1">
<section class="registerPage2">
<form method="post" action="#" onsubmit="" id="regTopfit" name="regTopfit">
<ul>
<input type="button" value="Full Registration" id="advReg">
<li>Nombre:</li>
<li><input id="i_firstname" type="text" name="firstname" placeholder="Firstname"><input id="i_lastname" type="text" name="lastname" placeholder="Lastname"></li>
<br>
<li><input type="text" id="i_dni" placeholder="Your ID"></li>
<li><input id="i_username" type="text" name="username" placeholder="Username"><span id="user-result"></span></li>
<li><input id="i_email" type="email" name="email" placeholder="Email address"></li>
<span class="extraFieldsRegistration">
<li><input type="text" id="i_phone" placeholder="Phone number"></li>
<li><input type="text" id="i_address" placeholder="Address"></li>
<li><input type="text" id="i_city" placeholder="City"></li>
<li><input type="text" id="i_postal" placeholder="Postal Code"></li>
<li><input type="text" id="i_province" placeholder="Province"></li>
<li><input type="text" id="i_creditcard" placeholder="Credit Card number"></li>
</span>
<li><div id="regMailError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li>Crear contraseña:</li>
<li><input id="i_pass1" type="password" name="pass1" placeholder="6-20 caracteres" ></li>
error<li><div id="regPLenError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input id="i_pass2" type="password" name="pass2" placeholder="Repite la contraseña" ></li>
error<li><div id="regPMatchError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="checkbox" name="offers" value="Yes">Quiero recibir las últimas novedades de TopFIT</li>
<li><input id="i_conditions" type="checkbox" name="conditions" value="accepted" >He leído y acepto la política de privacidad.</li>
error<li><div id="regCondError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="button" id="register" value="Crea tu cuenta"></li>
<li><span id="result"></span></li>
</ul>
</form>
</section>
</section>
</body>
</html>
Nothing to say about the view.
Controller/register.php
<?php
//REGISTER controller
require "../model/backend.php";
$username = $_POST["#i_username"];
$email = $_POST["#i_email"];
$password = $_POST["#i_pass1"];
$firstname = $_POST["#i_firstname"];
$lastname = $_POST["#i_lastname"];
$dni = $_POST["#i_dni"];
$phone = $_POST["#i_phone"];
$address = $_POST["#i_address"];
$city = $_POST["#i_city"];
$postal = $_POST["#i_postal"];
$province = $_POST["#i_province"];
$creditcard = $_POST["#i_creditcard"];
$dbcom = new dbInteraction;
$dbcom->register($firstname, $lastname, $email, $dni, $phone, $address, $city, $postal, $province, $creditcard, $username, $password);
$dbcom->conclose();
?>
In that case, as you can see, I pick the values of my inputs and then I call my register function passing all the arguments to perform the registration. I think that everything is cool here too.
model/backend.php
<?php
//model!
class dbInteraction{
private $connection;
private $server = "127.0.0.1";
private $s_user = "root";
private $s_password ="";
private $db = "youtube";
private $dni;
private $firstname;
private $lastname;
private $username;
private $password;
private $phone;
private $address;
private $city;
private $postal;
private $province;
private $creditcard;
public function __construct(){
$this->connection = new mysqli($this->server, $this->s_user, $this->s_password, $this->db);
if($this->connection->connect_errno){
// echo $db->connect_error;
die('Sorry, we are having problems.');
}
}
public function conclose(){
$this->connection->close();
}
public function login($user, $password){
$this->user = $username;
$this->password = $password;
$query = "SELECT id, firstname, lastname, password FROM people WHERE username = '".$this->user."' AND password = '".$this->password."' ";
$myquery = $this->connection->query($query);
if ($row = mysqli_fetch_array($myquery)){// or die($this->connection->error)) {
session_start();
$_session['id'] = $row['id'];
$_session['firstname'] = $row['firstname'];
$_session['lastname'] = $row['lastname'];
echo 'Signed in.' , '<br>';
echo 'Welcome' , $_session['firstname'];
}else{
echo 'Check your data and try again.';
}
}
public function register($firstname, $lastname, $email, $dni, $phone, $address, $city, $postal, $province, $creditcard, $username, $password){
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->email = $email;
$this->dni = $dni;
$this->phone = $phone;
$this->address = $address;
$this->city = $city;
$this->postal = $postal;
$this->province = $province;
$this->creditcard = $creditcard;
$this->username = $username;
$this->password = $password;
$query = "INSERT INTO users (username, email, password, firstname, lastname, dni, phone, address, city, postal, province, creditcard) VALUES ('$username','$email','$password', '$firstname', '$lastname', '$dni', '$phone', '$address', '$city', '$postal', '$province', $creditcard)";
$myquery = $this->connection->query($query);
if ($row = mysqli_fetch_array($myquery)) {
session_start();
$_session['id'] = $row['id'];
$_session['firstname'] = $row['firstname'];
$_session['lastname'] = $row['lastname'];
echo 'You have been correctly registered. Welcome to TopFIT ', $_session['firstname'];
}else{
echo 'Something went wrong.';
}
}
public function newPassword($email){
$this->email = $email;
}
}
We have to focus in the register function, which is that simple as it looks. I think that I'm sure of the syntax that I used there.
JS File
$(document).ready(function(){
var showFull = $(".extraFieldsRegistration");
var fullReg = $("#advReg")
fullReg.click(function(){
showFull.css('display','inline');
});
$("#register").click(function(){
var mailValue = $("#i_email").val();
var usernameValue = $("#i_username").val();
var passwordValue = $("#i_pass1").val();
var passwordValue2 = $("#i_pass2").val();
var conditionsValue = $("#i_conditions").val();
var fnameValue = $("#i_firstname").val();
var lnameValue = $("#i_lastname").val();
var dniValue = $("#i_dni").val();
var phoneValue = $("#i_phone").val();
var addrValue = $("#i_address").val();
var cityValue = $("#i_city").val();
var postalValue = $("#i_postal").val();
var provValue = $("#i_province").val();
var ccValue = $("#i_creditcard").val();
var __mailError = document.getElementById('regMailError');
var __passLenError = document.getElementById('regPLenError');
var __passMatchError = document.getElementById('regMatchError');
var __condError = document.getElementById('regCondError');
if (mailValue === '' || passwordValue === '' || passwordValue2 === '' || usernameValue === ''){
alert('completa todos los campos');
}else{
if (passwordValue != passwordValue2){
alert('contraseñas distintas');
}else{
if (document.getElementById('conditions').checked){
$.ajax({
type: "POST",
url: "../controller/register.php",
data: {
username: usernameValue,
email: mailValue,
password: passwordValue,
firstname: fnameValue,
lastname: lnameValue,
dni: dniValue,
phone: phoneValue,
address: addrValue,
city: cityValue,
postal: postalValue,
province: provValue,
creditcard: ccValue
},
success: function(msg){
$("#result").html(msg);
},
error:function(){
alert('error');
}
});
}else{
alert('Debes aceptar las condiciones');
}
}
}
}); //click del register
}); //document ready
Ok, definitely I think that here there are mistakes.
In the beginning, there is a piece of code that pretends to modify the property of a view span, turning that property (display) from none to inline.
I previously used this code in other files and functions and it was working correctly, now I have no idea why it doesn't work.
Then there is the form validator and after that, if everything goes fine, inside an if, I try to perform the communication to the other mvc files passing the arguments that should be recorded to my db.
You'll notice that there are a lot of unused variables, I know, I'll use these ones to modify the css (in case of error) of some divs that I have in the view, but I decided to use alerts to debug. So where you see alert, there will be a css modifier.
I think that everything has logic but despite of my things, it doesn't work.
I've been looking for solutions and I saw that using JSON, probably I'll save time, code and problems but I have to do this without json, at least for now.
Did you find some error? Do you have a better idea to build this system?
As always, I'll appreciate your help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- ADD / LOAD JQUERY HERE with the correct path -->
<script src="../js/jquery.js"></script>
</head>
<body>
<link rel="stylesheet" href="../css/register.css">
<script src="../js/valReg.js"></script>
<section class="registerPage1">
<section class="registerPage2">
<form method="post" action="#" onsubmit="" id="regTopfit" name="regTopfit">
<ul>
<input type="button" value="Full Registration" id="advReg">
<li>Nombre:</li>
<li><input id="i_firstname" type="text" name="firstname" placeholder="Firstname"><input id="i_lastname" type="text" name="lastname" placeholder="Lastname"></li>
<br>
<li><input type="text" id="i_dni" placeholder="Your ID"></li>
<li><input id="i_username" type="text" name="username" placeholder="Username"><span id="user-result"></span></li>
<li><input id="i_email" type="email" name="email" placeholder="Email address"></li>
<span class="extraFieldsRegistration">
<li><input type="text" id="i_phone" placeholder="Phone number"></li>
<li><input type="text" id="i_address" placeholder="Address"></li>
<li><input type="text" id="i_city" placeholder="City"></li>
<li><input type="text" id="i_postal" placeholder="Postal Code"></li>
<li><input type="text" id="i_province" placeholder="Province"></li>
<li><input type="text" id="i_creditcard" placeholder="Credit Card number"></li>
</span>
<li><div id="regMailError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li>Crear contraseña:</li>
<li><input id="i_pass1" type="password" name="pass1" placeholder="6-20 caracteres" ></li>
error<li><div id="regPLenError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input id="i_pass2" type="password" name="pass2" placeholder="Repite la contraseña" ></li>
error<li><div id="regPMatchError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="checkbox" name="offers" value="Yes">Quiero recibir las últimas novedades de TopFIT</li>
<li><input id="i_conditions" type="checkbox" name="conditions" value="accepted" >He leído y acepto la política de privacidad.</li>
error<li><div id="regCondError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="button" id="register" value="Crea tu cuenta"></li>
<li><span id="result"></span></li>
</ul>
</form>
</section>
</section>
</body>
</html>
I have a form with different inputs. On submit i use Ajax to send the data to a MySQL table. If the inputs are blank the jQuery validate plugin stops the submit action.
The POST submit works because i use Firebug and the response Ajax tells me that; but the data doesn't save in my database.
I don't know which part is causing the problem because in JS it doesn't tell me any issue.
My HTML/JS code looks like this:
$(document).ready(function() {
$("#ok").hide();
$("#formula").validate({
rules: {
nombre: {required: true},
mail: {required: true},
estado: {required: true},
imagen: {required:true,
extension:'jpeg|png|jpg|gif'},
checa:{required:true}
},
messages: {
nombre: "Debe introducir su nombre.",
mail:"Introduce una dirección de e-mail válido.",
estado : "Debes seleccionar tu estado donde resides.",
imagen : "Selecciona una imagen válida, jpg, jpeg, png o gif.",
checa: "Debes aceptar los terminos de uso y la política de privacidad"
},
submitHandler: function(form){
var dataString = 'nombre='+ nombre
+ 'mail=' + mail
+ '&estado=' + estado
+ '&imagen=' + imagen
+ '&checa=' + checa
$("#ok").show();
$.ajax({
type: "POST",
url:"envia.php",
data: dataString,
success: function(msg){
$("#ok").html("<strong>Mensaje enviado existosamente, nos pondremos en contacto a la brevedad.</strong>");
document.getElementById("nombre").value="";
document.getElementById("mail").value="";
document.getElementById("estado").value="";
document.getElementById("imagen").value="";
document.getElementById("checa").value="";
setTimeout(function() {$('#ok').fadeOut('fast');}, 3000);
}
});
}
});
});
<section class="wrapper">
<form method="post" name="formulario" id="formula" enctype="multipart/form-data">
<div id="ok"></div>
<label>Nombre:</label>
<input type="text" name="nombre" id="nombre" />
<label>Email:</label>
<input type="email" name="mail" id="mail" />
<label>Estado:</label>
<!--<div class="styled-select">-->
<select name="estado" id="estado">
<option value="">Selecciona tu estado:</option>
<option>Aguascalientes</option>
<option>Baja California</option>
<option>Baja California Sur</option>
<option>Campeche</option>
<option>Chiapas</option>
<option>Chihuahua</option>
<option>Coahuila</option>
<option>Colima</option>
<option>Distrito Federal</option>
<option>Durango</option>
<option>Guanajuato</option>
<option>Guerrero</option>
<option>Hidalgo</option>
<option>Jalisco</option>
<option>México</option>
<option>Michoacán</option>
<option>Morelos</option>
<option>Nayarit</option>
<option>Nuevo León</option>
<option>Oaxaca</option>
<option>Puebla</option>
<option>Querétaro</option>
<option>Quintana Roo</option>
<option>San Luis Potosí</option>
<option>Sinaloa</option>
<option>Sonora</option>
<option>Tabasco</option>
<option>Tamaulipas</option>
<option>Tlaxcala</option>
<option>Veracruz</option>
<option>Yucatán</option>
<option>Zacatecas</option>
</select>
<!--</div>
<div id="file">Chose file</div>-->
<input type="file" name="imagen" id="imagen" class="upload" />
<input type="checkbox" name="checa" id="checa" value="Acepto">Acepto los terminos y condiciones y la politica de privacidad
<input name="URLBack" type="hidden" id="URLBack" value="<?php echo "hhtp://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>" />
<input name="input" id="enviar" type="submit" value="Enviar" />
</form>
</section>
And my PHP file looks like this:
include 'conexion.php';
$con = conexion();
$nombre=substr($_POST['nombre'],0,2);
$sql= "SELECT MAX(id) FROM base_de_datos";
$rs=mysql_query($sql);
if(isset($rs) && mysql_num_rows($rs)>0)
{
$row=mysql_fetch_row($rs);
$num=$row;
mysql_free_result($rs);
}
$tumb = implode($num);
$sumando = $tumb + 1;
if ($_FILES["imagen"]["error"] > 0){
echo "ha ocurrido un error";
} else {
$permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
$limite_kb = 2000;
if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 2048){
$ruta = "imagenes/" . $_FILES['imagen']['name'];
if (file_exists($ruta)){
echo $_FILES['imagen']['name'] . ", este archivo existe";
}
else{
$temp = explode(".", $_FILES["imagen"]["name"]);
$newfilename = 'contest'. $sumando . '.' . end($temp);
move_uploaded_file($_FILES["imagen"]["tmp_name"], "imagenes/" . $newfilename);
}
}
}
$caracteres = "AABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
$numerodeletras=10;
$cadena = "";
for($i=0;$i<$numerodeletras;$i++)
{
$cadena .= substr($caracteres,rand(0,strlen($caracteres)),1);
}
$serie=$nombre.$sumando;
$este= date("Y/m/d");
echo $serie;
$_GRABAR_SQL = "INSERT INTO base_de_datos (nombre,email,estado,imagen,condiciones_de_uso,clave,fecha) VALUES ('$_POST[nombre]','$_POST[mail]','$_POST[estado]','$newfilename','$_POST[checa]','$serie','$este')";
mysql_query($_GRABAR_SQL);
$query=mysql_insert_id();
$headers = "MIME-Version: 1.0\r \n";
$headers .= "Content-type: text/html; charset=utf-8 \r \n";
$headers .= "Return-Path: ".$_POST['nombre']." <".$_POST['mail']."> \r \n";
$headers .= "From: OMA Plaza <noreply#example.com> \r \n";
$headers .= "Reply-To: ".$_POST['nombre']." <".$_POST['nombre']."> \r \n";
$headers .= "X-Priority: 1\r\n";
$mail = mysql_real_escape_string($_POST['mail']);
if ( function_exists( 'mail' ) )
{
echo 'mail() is available';
}
else
{
echo 'mail() has been disabled';
}
$asunto = "";
$confir = "Su mensaje fue enviado exitosamente, nos pondremos en contacto con usted a la brevedad";
$mensage = "---------------------------------- \n";
$mensage.= " Contacto \n";
$mensage.= "---------------------------------- \n";
$mensage.= "Nombre: ".$_POST['nombre']."\n";
$mensage.= "Clave Confirmación: ".$serie."\n";
$mensage.= "Email: ".$_POST['mail']."\n";
mail ($mail, $asunto, $mensage, $headers);
I have this form, it works perfectly but when submitted/failed it swaps to another page where the message is showed.
HTML
<form action="envio.php" method="post">
<label>Nombre </label>
<input type="text" name="name"><br>
<label>Email</label>
<input type="text" name="email"><br>
<label>Teléfono</label>
<input type="text" name="phone"><br>
<label>Mensaje</label>
<textarea name="message"></textarea><br>
<input id="submit" type="submit" name="submit" value="Enviar">
</form>
envio.php
if(isset($_POST['submit'])){
$to = "email#gmail.com"; // email destinatario
$from = $_POST['email']; // email del cliente
$name = $_POST['name'];
$phone = $_POST['phone'];
$mes = $_POST['message'];
$subject = "Formulario web";
$subject2 = "Copia de su formulario de consulta";
$message = $name . " con número de teléfono: " . $phone . " escribió lo siguiente:" . "\n\n" . $_POST['message'];
$message2 = "Aquí tiene una copia de su mensaje " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
$success = (preg_match("/^[0-9]{9}$/",$phone) && preg_match("/^[a-zA-Z]*$/",$name) && $mes!='' && filter_var($from, FILTER_VALIDATE_EMAIL));
if ($success){
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // copia para el cliente
echo "Formulario enviado. Muchas gracias " . $name . ", en breve contactaremos con usted.";
}
else {
echo "Lo sentimos, se ha producido un error al enviar el formulario, revise su contenido y vuelva a intentarlo.";
}}
I just want to show the messages in the if/else under the 'send' button after click it, without refresh, I think it can be done with JQuery/Vanilla but I have no clue. How can JS know if the form was submitted successfully? How can I tell JS where to insert the message?
Further to my comments and because it's hard to explain in such a little space:
page1.php
<!-- Name the form myform as an id -->
<form action="page2.php" method="post" id="myform">
<label>Nombre </label>
<input type="text" name="name"><br>
<label>Email</label>
<input type="text" name="email"><br>
<label>Teléfono</label>
<input type="text" name="phone"><br>
<label>Mensaje</label>
<textarea name="message"></textarea><br>
<input id="submit" type="submit" name="submit" value="Enviar">
</form>
<!-- Invisible response container -->
<div id="response"></div>
<script>
$("#myform").submit(function() {
$.ajax({
// PHP page
url : 'page2.php',
// Takes all data from form
data: $("#myform").serialize(),
// Puts response into the container
success: function(response) {
$("#response").html(response);
}
});
// This stops the page from reloading on submit
return false;
});
</script>
page2.php
if(isset($_POST['submit'])){
$to = "email#gmail.com"; // email destinatario
$from = $_POST['email']; // email del cliente
$name = $_POST['name'];
$phone = $_POST['phone'];
$mes = $_POST['message'];
$subject = "Formulario web";
$subject2 = "Copia de su formulario de consulta";
$message = $name . " con número de teléfono: " . $phone . " escribió lo siguiente:" . "\n\n" . $_POST['message'];
$message2 = "Aquí tiene una copia de su mensaje " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
$success = (preg_match("/^[0-9]{9}$/",$phone) && preg_match("/^[a-zA-Z]*$/",$name) && $mes!='' && filter_var($from, FILTER_VALIDATE_EMAIL));
if ($success){
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // copia para el cliente
echo "Formulario enviado. Muchas gracias " . $name . ", en breve contactaremos con usted.";
}
else {
echo "Lo sentimos, se ha producido un error al enviar el formulario, revise su contenido y vuelva a intentarlo.";
}
}
first I have to use PHP4 and SMARTY2. Yep I know it is very bad :-/ but we're unable to upgrade cause the existing systems need that environment... :#
I want to code a admin login with jquery's load and php.
There is a 3 part Login cause of the tpl system of smarty: a smarty login (with php and tpl) a forgotten php and another login php. I can only load php with jquery: not tpl and php
the first login is include in our frame.tpl
the other 2 can only used with a combination of php and html cause of the load()
I can't get the POSTs from the combinatet php's could u pls tell me how I can use it?
so here the code where i include the login.tpl:
<div id='rightcolumn'>
<div class='admin'>
<h3>ADMINISTRATOR</h3>
{include file='login.tpl'}
</div>
the login.tpl
<form method="POST">
{literal}
<script type="text/javascript">
$(document).ready(function(){
$("#load").click(function(){
$("#dynamic").load("././content/pw_lost.php");
return false;
});
});
</script>
{/literal}
<br />
<div id="dynamic">
<!--[if IE]>
Pers.Nr.:
<br /><input type="text" name="persnr" style="width:150px;" value="Pers.Nr."
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value=='')this.value=this.defaultValue;"/>
<br />
<br />
Passwort:
<br /><input type="password" name="password" style="width:150px;" value="***********"
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value=='')this.value=this.defaultValue;"/>
<br />
<br /><input type="submit" name="login" value="anmelden" />
<![endif]-->
<!--[if !IE]> -->
<fieldset id="inputs" class="field_login">
<input id="persnr" name="persnr" type="text" placeholder="Pers.Nr.">
<input id="password" name="password" type="password" placeholder="Password">
</fieldset>
<br />
<button type="submit" name="login" value="anmelden" class="myButton">Anmelden</button>
<br />
<!--<![endif]-->
<br />
<br /><div id="load">Passwort vergessen?</div>
<br />
<br />
</div>
</form>
here the forgotten.php:
and here is the problem I can't use the php block (if I don't use the first if(isset()) i get a blank page... and if i submit the whole page is reloading and didn't get any POSTs
<?php
if(isset($_POST['persnr'])) {
if (empty($_POST['persnr'])) {
$SMARTY->assign('message', 'Bitte füllen Sie alle Felder aus.');
} else {
$TMP_PERSNR = strtolower($DB->escape($_POST['persnr']));
$query = "SELECT * FROM TAB_MITARBEITER WHERE lower(NPERSNR)='$TMP_PERSNR'";
$res = $DB->query($query, TRUE);
unset($query);
if ($res) {
// also wenn es den Mitarbeiter gibt
$pool = "qwertzupasdfghkyxcvbnm";
$pool .= "23456789";
$pool .= "WERTZUPLKJHGFDSAYXCVBNM";
srand ((double)microtime()*1000000);
for($index = 0; $index < 8; $index++) {
$newpassword .= substr($pool,(rand()%(strlen ($pool))), 1);
}
$Name = "SAZ Support"; //senders name
$email = $res[0]['VCMAIL']; //senders e-mail adress
$recipient = $res[0]['VCMAIL']; //recipient
$subject = "SAZ - neues Passwort"; //subject
$header = "From: ". $Name . " <" . ">\r\n"; //optional headerfields
$mail_body = ucfirst(strtolower($res[0]['VCNAME'])) ." ". ucfirst(strtolower($res[0]['VCVORNAME'])) . ",\n\n";
$mail_body .= "gerne möchten wir Ihnen ein neues Passwort zusenden. Ihr neues Passwort lautet: $newpassword\n\n";
$mail_body .= "Sie können Ihr Passwort jederzeit unter 'Einstellungen' in der SAZ ändern.\n\n";
$mail_body .= "Wenn Sie kein neues Passwort angefordert haben und Sie glauben, dass es sich um Missbrauch der Funktion handelt, dann wenden Sie sich bitte mit dieser E-Mail an die Systemadministration.\n\n";
$mail_body .= "Mit freundlichen Grüßen\n\n";
$mail_body .= "Ihr SAZ Support\n\n";
$mail_body .= "\n";
$mail_body .= "Abfrage von folgender Maschine gestartet: {$_SERVER['REMOTE_ADDR']}\n\n";
// change pw:
$newpassword = md5($newpassword);
$query = "UPDATE TAB_MITARBEITER SET VCPASSWORT='$newpassword' WHERE lower(NPERSNR)='$TMP_PERSNR'";
$res = $DB->query($query, FALSE);
unset($query);
if (mail($recipient, $subject, $mail_body, $header) === TRUE) {
$SMARTY->assign('message', 'Passwort zugesendet.');
}
} else {
$SMARTY->assign('message', 'Fehler. Mitarbeiter nicht gefunden.');
}
}
}
?>
//HTML starts
<form method="POST">
<script type="text/javascript">
$(document).ready(function(){
$("#load").click(function(){
$("#dynamic").load("././content/2_login.php");
return false;
});
});
</script>
<div id='dynamic'>
<div id='justify'>
Wenn Sie ihr Passwort vergessen haben, oder Sie noch kein Passwort vergeben haben, dann geben Sie hier bitte Ihre Personalnummer ein und wir senden ihnen per Email umgehend ein (neues) Passwort zu (sofern ein Benutzer für Sie bereits angelegt wurde).<br /><br />
</div>
Pers.Nr:
<br />
<input type="text" name="persnr">
<br />
<br />
<input type="submit" name="lostpw" value="Passwort anfordern" />
<br />
<br />
<div id="load">Ich möchte mich einloggen.</div>
</div>
</form>