Hello, I've recently been building a contact page for my html website and it seems to not send my message to my email at all!
It continues with ->
I am a little confused also why its not sending the message, and the default errors don't pop up with saying "this is required to be filled".
Here is my PHP code (sending the message) :
<?php
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$phone = htmlspecialchars($_POST['phone']);
$website = htmlspecialchars($_POST['website']);
$message = htmlspecialchars($_POST['message']);
if(!empty($email) && !empty($message)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$receiver = "MYEMAILHERE";
$subject = "From: $name <$email>";
$body = "Name: $name\nEmail: $email\nPhone: $phone\nWebsite: $website\n\nMessage:\n$message\n\nRegards,\n$name";
$sender = "From: $email";
if(mail($receiver, $subject, $body, $sender)){
echo "Your message has been sent";
}else{
echo "Sorry, failed to send your message!";
}
}else{
echo "Enter a valid email address!";
}
}else{
echo "Email and message field is required!";
}
?>
Here is my JS code (creating the message) :
const form = document.querySelector("form"),
statusTxt = form.querySelector(".button-area span");
form.onsubmit = (e)=>{
e.preventDefault();
statusTxt.style.color = "#0D6EFD";
statusTxt.style.display = "block";
statusTxt.innerText = "Sending your message...";
form.classList.add("disabled");
let xhr = new XMLHttpRequest();
xhr.open("POST", "src/php/message.php", true);
xhr.onload = ()=>{
if(xhr.readyState == 4 && xhr.status == 200){
let response = xhr.response;
if(response.indexOf("required") != -1 || response.indexOf("valid") != -1 || response.indexOf("failed") != -1){
statusTxt.style.color = "red";
}else{
form.reset();
setTimeout(()=>{
statusTxt.style.display = "none";
}, 3000);
}
statusTxt.innerText = response;
form.classList.remove("disabled");
}
}
let formData = new FormData(form);
xhr.send(formData);
}
Here is my HTML code before end of my body (linking the js) :
<script src="src/js/contact.js"></script>
Is there anything i'm missing? Could it be not linking correctly? Im also sending this using an online website, not locally.
Using Githubpages, which does not support PHP. That is the problem.
Related
I'm doing contact form on my portfolio website. I made working PHP form and also working javascript validation but when I tried to add both to work one after another it crash.
To sumarize I would like to know how to call contactForm.php after the all inputs are valid.
Here is my JS code:
function formValidator(){
const form = document.getElementById('form');
const name = document.getElementById('name');
const email = document.getElementById('email');
const message = document.getElementById('message');
let errorStatus = true;
form.addEventListener('submit',(e) => {
e.preventDefault(); // here I stop submiting
checkInputs(); // here I check validation of inputs
if(errorStatus == true){ //if its ok I run this
console.log("Its ok")
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", "contactForm.php", true);
xhttp.send();
}
else{
form.scrollIntoView({ behavior: 'smooth'});
}
});
function checkInputs(){
const nameValue = name.value.trim();
const emailValue = email.value.trim();
const messageValue = message.value.trim();
if(nameValue === ''){
setErrorFor(name, "Proszę podać imię");
} else{
setSuccessFor(name);
}
}
function setErrorFor(input, message){
const formControl = input.parentElement;
const errorContent = formControl.querySelector('.error-message');
const alertVisibility = formControl.querySelector('.alert');
errorContent.innerText = message;
alertVisibility.style.visibility = "visible";
errorStatus = false;
}
function setSuccessFor(input){
const formControl = input.parentElement;
const alertVisibility = formControl.querySelector('.alert');
alertVisibility.style.visibility = "hidden";
errorStatus = true;
}
}
I added this code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", "contactForm.php", true);
xhttp.send();
Here is contactForm.php
<?php
// Get data from form
$name = $_POST['name'];
$email= $_POST['email'];
$message= $_POST['message'];
$to = "piotr.brze95#gmail.com";
$subject = "Nowe zlecenie od " . $name . " z strony MelonStudio";
// The following text will be sent
// Name = user entered name
// Email = user entered email
// Message = user entered message
$txt ="Name = ". $name . "\r\n Email = "
. $email . "\r\n Message =" . $message;
$headers = "From: noreply#demosite.com";
if($email != NULL) {
mail($to, $subject, $txt, $headers);
}
?>
and it doesnt work. I also made some research to find the best way to aproach forms and this is what I ended with. PHP form with JS Validation but I can't combine them.
You can also check this website here: My Portfolio and the contact form is in the end of the page.
Update 29.12
After some code updating I managed to send email correctly.
Here is my JS code that check if there is no error and fetching php file:
e.preventDefault();
checkInputs();
if(errorStatus === true){
console.log("Its ok");
phpFetcher();
window.location.href = "https://melon.studio/success-page.html";
} else{
form.scrollIntoView({ behavior: 'smooth'});
}
});
function phpFetcher(){
form.addEventListener('click', function(event){
const formattedFormData = new FormData(form);
postData(formattedFormData);
});
async function postData(formattedFormData){
const response = await fetch('contactForm.php',{
method: 'POST',
body: formattedFormData
});
}
The problem is that JS doesn't wait for executing the php file and redirecting the website instantly.
header("Location:index.html");. this is the first issue. You should remove it. The second issue is you didn't send response for ajax call. You should send response for ajax request by echo "Your message has been sent". In your case, you can return the result of mail function.Please add this code in contactForm.php.
if(mail($to, $subject, $txt, $headers)) {
echo "Your message has been sent";
} else {
echo "Enter the valid email address"
}
I am using ajax to resend the verification email to my user who registered on-site. The code is working fine on my chrome browser but not on firefox. In the Firefox networking tab, I can see it blocked my post request. How can I solve this issue, I am not getting any kind of errors, it's just not working.
Firefox networking tab screenshot.
And this is how I am using ajax, I can't use jQuery that's why I am using vanilla js method.
<!DOCTYPE html>
<head>
<title>Verification</title>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("email_send").addEventListener("click", function() {
function postAjax(url, data, success) {
var params = typeof data == 'string' ? data : Object.keys(data).map(
function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
).join('&');
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
return xhr;
}
postAjax('send_verification.php', { }, function(data){
if (data === "verified"){
window.location ="login.php";
} else if (data === "sent"){
document.getElementById('mydiv').innerHTML = '<span class="prego">Sent Again...</span>';
}else if (data === "error"){
document.getElementById('mydiv').innerHTML = '<span class="prego">Unable Sent Again...</span>';
}
document.getElementById('mydiv').innerHTML = '<span class="prego">Just checking</span>';
console.log(data+" getting something");
});
});
</script>
</head>
<body>
<div class="text-center">
<img src="images/sucess.gif" alt="sucess">
<h4>A verification link have been sent to your email, Please flow instructions to activate your account.</h4>
<br>
<h4 class="text-center">Didn't get one? <a id="email_send" action="send_mail" href=""> click to resend.</a> </h4>
<div id="mydiv">
</div>
</div>
</body>
</html>
Also, I tried fetch() method for this, but fetch is also getting blocked for some reason.
This is the request I am making using ajax.
<?php
session_start();
include 'connection.php';
if(isset($_SESSION['email'])){
$email = $_SESSION['email'];
$email_check = $con->prepare("SELECT * FROM `user_reg` WHERE email =?");
$email_check->bind_param("s",$email_i);
$email_i = $email;
$email_check->execute();
$result = mysqli_stmt_get_result($email_check);
$email_count = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
$token = bin2hex(random_bytes(25));
if ($email_count>0){
if($row['status']==="inactive"){
$insert_query = $con->prepare("UPDATE `user_reg` SET `token`=? WHERE `email`=?");
$insert_query->bind_param("ss", $token_i, $email_i);
$token_i = $token;
$email_i = $email;
$query = $insert_query->execute();
if ($query){
$username = $row['username'];
$url = "";
$subject = "Email verification";
include 'templates/email_con.php';
include 'templates/email_verifiy_tempate.php';
if (mail($email, $subject, $body, $headers)){
$_SESSION['msg']="Check your email for activation of your account";
echo "Email Sent...";
header('location:login.php');
}else{
echo "Email not sent, please check your email";
}
$insert_query->close();
}else{
echo "error";
}
}else{
$_SESSION['msg']="You are alredy verified, login to continue";
echo "verified";
}
}else{
echo "Email dosen't exists, please sign up";
}
}else {
header('location:login.php');
}
We are running a website on a local server. After entering the required data into contact form and clicking the button Send, we get the "500 Internal Server Error". I'm assuming this relates to PHP mail configuration for local servers.
PHP:
<?php
if(isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["msg"])){
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$msg = nl2br($_POST["msg"]);
$to = "info#companyname.com";
$from = $email;
$message = "<b>Name:</b> ".$name." <br><b>E-mail:</b> ".$email." <br><b>Subject:</b> ".$subject." <br><p> ".$msg." </p>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: $from" . "\r\n";
if(mail($to, $subject, $message, $headers)){
echo "Success";
}else{
echo "The server failed to send the message. Please try again later.";
}
}
?>
JS:
function _(id){return document.getElementById(id);}
function submitForm(){
_("submit").disabled = true;
_("status").innerHTML = "Please wait...";
var formdata = new FormData();
formdata.append("name", _("name").value);
formdata.append("email", _("email").value);
formdata.append("subject", _("subject").value);
formdata.append("msg", _("msg").value);
var ajax = new XMLHttpRequest();
ajax.open("POST", "contact.php");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
if(ajax.responseText == "Success"){
_("status").innerHTML = "";
_("response").innerHTML = "Your message has been successfully sent.";
}else{
_("status").innerHTML = ajax.responseText;
_("submit").disabled = false;
}
}
}
ajax.send(formdata);
}
I think your problem is caused by SMTP server configuration. There are no syntax errors in the code. If the php would be in wrong folder it would return 404 error not 500.
Try to comment the if/else part of the php file just to make sure the other parts of the file are working.
Solved. The problem was with the configuration of our local server which runs on MS IIS.
I was following a tutorial on youtube about setting up a contact page and for some reason I'm getting an error message in the console saying submitForm is not defined when I press the submit. My issue is I got the same code to work on another website but when I copy the exact same code it doesn't work. Here's my js code:
function _(id){ return document.getElementById(id); }
function submitForm(){
_("mybtn").disabled = true;
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "n", _("n").value );
formdata.append( "e", _("e").value );
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "example_parser.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("my_form").innerHTML = '<h2>Thanks '+_("n").value+', your message has been sent.</h2>';
} else {
_("status").innerHTML = ajax.responseText;
_("mybtn").disabled = false;
}
}
}
ajax.send( formdata );
}
and here is my php code:
<?php
if( isset($_POST['n']) && isset($_POST['e']) && isset($_POST['m']) ){
$n = $_POST['n']; // HINT: use preg_replace() to filter the data
$e = $_POST['e'];
$m = nl2br($_POST['m']);
$to = "skoolboi434#gmail.com";
$from = $e;
$subject = 'Contact Form Message';
$message = '<b>Name:</b> '.$n.' <br><b>Email:</b> '.$e.' <p>'.$m.'</p>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
if( mail($to, $subject, $message, $headers) ){
echo "success";
} else {
echo "The server failed to send the message. Please try again later.";
}
}
?>
As you can see I defined the function but getting that error. Any help would be greatly appreciated.
I'm not sure what I did so I started over and rewatched the tutorial a few times and got it to work.
I am using the jQuery Form Post plugin from malsup, with the following code:
//Post a form
function PostForm(FormID, Target) {
var $t = Math.round(new Date().getTime() / 1000);
try{
var options = {
target: Target,
beforeSubmit: function () {
jQuery(Target).html('<div id="frmLoadingImageWrapper"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>');
jQuery(Target).slideDown('slow');
},
success: function (html) {
setTimeout(function () {
jQuery(Target).html(html);
jQuery(FormID)[0].reset();
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
}, 100);
},
error: function(e){
var $html = e.responseText;
jQuery(Target).html($html);
jQuery(Target).slideDown('fast');
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
setTimeout(function() {
jQuery(Target).slideUp('fast');
}, 3500);
}
};
jQuery(FormID).ajaxSubmit(options);
}catch(err){
alert(err.message);
}
}
When I submit my form to /inc/mail.php the actuall PHP code shows in my Target instead of getting processed.
How can I fix this issue? All other PHP scripts work as they should, including other ajax pulled php scripts.
Here is the mailer code, it's using PHP SMTP
<?
require("/inc/class.phpmailer.php");
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('m/d/Y');
$time = date('H:i:s');
//form data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$captcha = $_POST['secAnswer'];
$valid = true;
if(!is_string($email) || !(strlen($email)>0) || !ValidateEmail($email)){
$valid = false;
}
if(!is_string($name) || !(strlen($name)>0) || !ValidateText($name)){
$valid = false;
}
if(!is_string($message) || !(strlen($message)>0) || !ValidateText($message)){
$valid = false;
}
if(!CheckCAPTCHA($captcha)){
$valid = false;
}
sleep(1.5);
if($valid){
$mail = new PHPMailer();
$mail->IsMail(); // send via SMTP
$mail->From = $email; // SMTP username again
$mail->AddAddress("kevin#pirnie.us"); // Your Adress
$mail->Subject = "New mail your site!";
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Body = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Email Address: </strong> {$email} </p>
<p><strong>Phone: </strong> {$phone} </p>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
if(!$mail->Send())
{
echo "Mail Not Sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Mail Sent";
}else{
echo "Mail Not Sent. Please make sure all fields are filled out correctly.";
}
function ValidateEmail($str){
$atIndex = strrpos($str, "#");
if (is_bool($atIndex) && !$atIndex){
return false;
}else{
if (filter_var($str, FILTER_VALIDATE_EMAIL)) {
$domain = substr($str, $atIndex + 1);
return (checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"));
}else{
return false;
}
}
}
function ValidateText($str){
return (bool)preg_match("/^[a-zA-Z0-9 _-]+$/", $str);
}
function CheckCAPTCHA($str){
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/captcha.class.php');
$csc = new ResponsiveCaptcha();
if($csc->checkAnswer($str)){
return TRUE;
}else{
return FALSE;
}
}
Make sure that your server supports the short PHP open tag <?
If not : change the short_open_tag value in your php.ini file
or use <?php