Php Contact Form Reference error - javascript

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.

Related

HTML Contact Page Not Sending Email

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.

500 Internal Server Error (Contact Form, 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.

How should I properly structure this PHP mailing script?

I am attempting to send the collected value's of a html form as an email to myself via PHP & Ajax. For some reason, I am able to update the UI with a success alert, however there's no actual email sent when I check my inbox. I am under the impression that my PHP script may be ill-structured, because when I log the results of my js function, all of the form values have been correctly captured.
Here is the JS:
function _(id){ return document.getElementById(id); };
function submitForm(){
var formdata = new FormData();
formdata.append( "first-name", _("first-name").value );
formdata.append( "last-name", _("last-name").value );
formdata.append( "email", _("email").value );
formdata.append( "subject", _("subject").value );
formdata.append( "message", _("message").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "email_me.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
alert("Hey! It Worked!!");
} else {
// display error
}
}
}
ajax.send( formdata );
// Display the key/value pairs
for (var pair of formdata.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
}
And Here is the php script (email_me.php file)
<?php
if(isset($_POST['first-name'], $_POST['last-name'], $_POST['email'], $_POST['subject'], $_POST['message'])){
$name = $_POST['first-name'];
$email = $_POST['email'];
$m = nl2br($_POST['message']);
$to = "me#gmail.com";
$from = $email;
$subject = $_POST['subject'];
$message = '<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.";
}
}
?>
What seem's to be the issue? Im running the current version of Apache with a localhost, using MAMP Pro btw.
Here are the server logs:
Marker - Aug 23, 2016, 12:34:32 PM
Aug 23 12:35:24 MacBookAir postfix/master[7884]: daemon started -- version 2.11.0, configuration /etc/postfix
Aug 23 12:36:24 MacBookAir postfix/master[7884]: master exit time has arrived
Aug 23 12:36:24 MacBookAir postfix/master[7885]: daemon started -- version 2.11.0, configuration /etc/postfix
Aug 23 12:37:24 MacBookAir postfix/master[7885]: master exit time has arrived
Aug 23 12:37:24 MacBookAir r postfix/master[7886]: daemon started -- version 2.11.0, configuration /etc/postfix
update you php code and check it will work
if(isset($_POST['first-name'], $_POST['last-name'], $_POST['email'], $_POST['subject'], $_POST['message'])){
$name = $_POST['first-name'];
$email = $_POST['email'];
$m = nl2br($_POST['message']);
$message = '<p>Name => '.$name.' <br/> Email =>'.$email.'<br /> Message =>'.$m.'</p>';
$to = "me#gmail.com";
$subject = $_POST['subject'];
$headers = "From: noreply#something.com\r\n"; // use \r\n
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; // use \r\n
$headers.= "X-Priority: 1\r\n";
if( mail($to, $subject, $message, $headers) ){
echo "success";
} else {
echo "The server failed to send the message. Please try again later.";
}
}

success does not appear

Help to make a conclusion successful transmission of data. I tried in different ways, but it does not work. By clicking on the "Send" button the data is sent, but the message "Data sent successfully".
I need it to form disappeared and instead of it there was a message "Data sent successfully"
submitHandler: function(form){
var $form = $(form);
$.post('form.php', $form.serialize(), function(data){
if (!data || data.status !== 'ok') {
$form.find('input').addClass('error');
return false;
}
forms.fadeOut('slow', function(){
$('.form--success').fadeIn('fast');
});
}, 'json');
return false;
}
});
form.php
if(isset($_POST['submit'])) {
$to = "example#example.com";
$subject = "Contact Form";
$phone = $_POST['phone'];
$mail = $_POST['mail'];
$headers = "From: $phone<$mail>\r\n";
$body = "From: $phone<$mail>\r\n Phone Number: $phone\n E-Mail: $mail\n";
mail($to, $subject, $body, $headers);
exit();
}
http://37.230.210.96/ - testing site
You're not targeting the right element to fade out. You have:
var form = $(form);
To fade that out you would use this:
form.fadeOut('slow', function(){
$('.form--success').fadeIn('fast');
});
forms != form

getting a 500 error when submitting email but email still goes through

I am lost on why i am getting this internal error(500). My email info still go through when i click submit. The only problem i have is that the ajax success method is not being called so basically my callback function is never getting called on. Any help would be greatly appreciated. I have been pulling my hair out for hours on this problem.
My scipt-ajax call:
emailValidation: function(e){
e.preventDefault();
$('body, html').animate({scrollTop:0},"slow");
var valid = '';
var name = $("#f_name").val();
var email = $("#f_email").val();
var message = $("#f_message").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(name === '' || name.length <= 2){
valid += '<p class="error">Name must be longer than 2 char.</p>';
}
if(message === '' || message.length <= 5){
valid += '<p class="error">Message must be longer than 5 char.</p>';
}
if (!(email).match(emailReg)){
valid += '<p class="error">Invalid Email</p>';
}
if (valid !== ''){
$('#form-messages').html(''+valid+'').fadeIn();
}
else {
var formData = $("#contact").serialize();//Value for sanitized form values to be paased to email.php. Value returns an array
portfolio.submitEmail(formData);
}
},
submitEmail: function(formData){
console.log(formData);
//$('#form-messages').html("Proccessing...<img src='img/processing_bar.png' alt='Proccessing' />").fadeIn('fast');
$('body, html').animate({scrollTop:0},"fast");
$.ajax({
type: 'POST',
url: 'mailer.php',
data: formData,
dataType: 'json',
success: function(result){
console.log(result.statusText);
if(result.statusText === 'OK'){
console.log('jam');
// Make sure that the formMessages div has the 'success' class.
$('#form-messages').removeClass('error');
$('#form-messages').addClass('success');
// Set the message text.
$('#form-messages').html('<p class="success">Message has been sent succesfully! Thank you '+ $('#f_name').val() +', a response will be returned in less than one business day.</p>');
$("#contact").fadeOut('slow').remove();
$('body, html').animate({scrollTop:0},"fast");
}
},
error: function(error){
console.log(error.statusText);
if(error.statusText === 'OK'){
// Make sure that the formMessages div has the 'success' class.
$('#form-messages').removeClass('error');
$('#form-messages').addClass('success');
// Set the message text.
$('#form-messages').html('<p class="success">Message has been sent succesfully! Thank you '+ $('#f_name').val() +', a response will be returned in less than one business day.</p>');
$("#contact").fadeOut('slow').remove();
$('body, html').animate({scrollTop:0},"fast");
}
},
});
},
Here is my mail.php file:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$em_name = strip_tags(trim($_POST["name"]));
$em_name = str_replace(array("\r","\n"),array(" "," "),$em_name);
$em_email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$em_message = $_POST["message"];
$em_phone = $_POST['phone'];
$em_website = $_POST['website'];
$em_hear = $_POST['hear'];
$em_startdate = $_POST['startdate'];
$em_budget = $_POST['budget'];
$to = 'theller5567#gmail.com';
$subject = 'Website Change Request';
$headers = "From: " . $em_email . "\r\n";
$headers .= "Reply-To: ". $em_email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Build the email content.
$message = "<h3>Name: ". $em_name. "\n</h3>";
$message .= "<h3>Message: ". $em_message. "\n</h3>";
$message .= "<p>Budget: ". $em_budget. "\n</p>";
$message .= "<p>Start Date: ". $em_startdate. "\n</p>";
$message .= "<p>How did you hear about us?: ". $em_hear. "\n</p>";
$message .= "<p>Email: ". $em_email. "\n</p>";
$message .= "<p>Phone: ". $em_phone. "\n</p>";
$message .= "<p>Website: ". $em_website. "\n</p>";
if (mail($to, $subject, $message, $headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

Categories