500 error on localhost when submitting form using AJAX and PHP - javascript

I'm fairly new to PHP and I'm having trouble sending test emails out from my local host.
I have a 3 field form where I'm hoping that I can have a user submit the form & be able to see a success message without the page refreshing. I get the error message that I have set in the code but for some reason, I'm unable to actually get the emails to send/have a success message appear.
Here's my code:
js
jQuery( document ).ready( function( $ ) {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#name, #email, #number').val('');
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
mailer.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$number = trim($_POST["number"]);
if ( empty($name) OR empty($number) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
exit;
}
$recipient = "example#example.co.uk";
$subject = "$name has given you their details to call them back";
$email_content = "
<html>
<style>
body {
background-color: white;
}
.email-container{
background-color:#c1c1c1;
max-width:400px;
margin:0 auto;
padding:30px 10px;
border-radius:10px;
border: 2px solid #515151;
}
</style>
<body>
<div class="email-container">
Dear example, <br />
<br />
A potential client has requested a call back. Their details are as follows: <br />
<br />
Name: $name\n <br />
Email: $email\n\n <br />
Telephone: \n$numer\n
</div>
</body>
</html>"
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
HTML
<form class="requestcall-form" id="ajax-contact" method="post" action="mailer.php">
<input type="text" id="name" name="name" placeholder="Full Name" required>
<input type="text" id="email" name="email" placeholder="Email Address" required>
<input type="text" id="number" name="number" placeholder="Contact number" required>
<input class="submit" type="submit" name="submit" value="Submit">
</form>
<div id="form-messages"></div>

there is something wrong with how you output $email_content. String is not formatted correctly
check the <div class="email-container"> and change it to <div class='email-container'>
also, add a (;) after your $email_content

The other answer is correct, I thought I'd offer a better solution for dealing with large blocks of text, heredoc strings. No worrying about unescaped quotes ruining your day. Using this, your code would look like this:
...
$recipient = "example#example.co.uk";
$subject = "$name has given you their details to call them back";
$email_content = <<< HTML
<html>
<style>
body {
background-color: white;
}
.email-container{
background-color:#c1c1c1;
max-width:400px;
margin:0 auto;
padding:30px 10px;
border-radius:10px;
border: 2px solid #515151;
}
</style>
<body>
<div class="email-container">
Dear example, <br />
<br />
A potential client has requested a call back. Their details are as follows: <br />
<br />
Name: $name <br />
Email: $email <br />
Telephone: $numer
</div>
</body>
</html>
HTML;
$email_headers = "From: $name <$email>";
...

Related

Hide "submit" button once a form is sent successfully, then show success message

At the moment I have a working contact form. I'd like to hide the "submit" button of my form when the form is sent successfully and then display a success message.
At the moment it redirects, which I've left for the purpose of this request.
I've tried multiple solutions, tweaking of the js but js sure isn't my strong point. I've left the CSS in also for the purpose of this question as I believe that will be the route I need to go down.
<< ? php
if (empty($_POST) === false) {
session_start();
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$errors = array();
if (isset($_POST['name'], $_POST['email'], $_POST['message'])) {
$fields = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
);
foreach($fields as $field => $data) {
if (empty($data)) {
//$errors[] = "The " . $field . " is required";
$errors[] = "Please fill-in the form correctly";
break 1;
}
}
if (empty($errors) === true) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid e-mail address";
}
}
if (empty($errors) === true) {
$name = test_input($_POST['name']);
$email = test_input($_POST['email']);
$message = test_input($_POST['message']);
$to = "example#example.com";
$subject = "example | You have a new message from ".$name;
$body = ......
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
$data = $_POST['name'].
' == Email: '.$_POST['email'].
' Message: '.$_POST['message'].
"\r\n";
$ret = file_put_contents('entries.log', $data, FILE_APPEND | LOCK_EX);
if ($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
} else {
header('location: ../sendmail/redirect.html');
}
$headers = "MIME-Version: 1.0".
"\r
#thank-you-message {
display: none;
}
#thank-you-message.show {
display: block;
}
<form action="/sendmail.php" method="post" onsubmit="return checkform(this);">
<input type="text" name="name" id="" autocomplete="off" placeholder="Name" required><br>
<input type="email" name="email" id="" autocomplete="off" placeholder="E-mail" required><br>
<textarea name="message" id="" cols="30" rows="10" placeholder="Type Your Message" required></textarea>
<button type="submit">Send</button>
</form>
<p id="thank-you-message">Thank you for contacting us. We will be in touch with you soon.</p>
You can use JavaScript to hide this button or generate this site by using PHP.
You have two possibilities, cookies or sessions.
Check if cookie or session is set, if not display the button or form, if is set hide button or form.
This can be done within a If/Else condition and a simple „print“ function.
Like (PHP)
IF (isset xxx = true) {
// print nothing
// redirect to page xxx.html
// or print Text like Lorem Ipsum
}
else {
print '<form method=“POST“ action=“form.php“> … </form>';
}
After submit the form you have to set a session or cookie in „form.php“.
When a user come back to this site, the site will check the cookie or session and print the form or not.
You have to change the IF/Else condition to your needs.
You can also print a „Thank you page“ or something else you want, you can also redirect to a other page by the header function within php.
Quick fix, you could try structuring your code in this format if using PHP
function save() {
$('.btn-danger').hide()
var number_i = $('#number_i').text();
var date_s = $('#date_s').text();
var name_p = "<?php echo $_POST['product_name']; ?>";
if (number_i != '___') {
$.post('saveEntry.php', {number: number_i, date: date_s, name: name_p}, function() {
$('#confirmation').text('Info: the data was saved!');
$('#confirmation').attr('class', 'alert alert-success');
})
} else {
alert('Introdu Numar Bon Fiscal!');
}
};
No need for JS for this. Assuming your form is parsing properly, you can add the following styles to your stylesheet.
#thank-you-message {
display: none;
}
button:focus ~ #thank-you-message {
display: block;
}
I removed your PHP and the rest of your form so that you can see a demonstration. See below:
Edit ~ added sample JS for the button to change text upon form submission. (Doesn't affect p displaying on button click)
function form_success() {
document.getElementById("myform").submit();
document.getElementById("btn").innerHTML = "Sent!";
}
#thank-you-message {
display: none;
}
button:focus {
background-color: green;
color: white;
}
button:focus~#thank-you-message {
display: block;
}
<form action="/sendmail.php" method="post" onsubmit="return checkform(this);" id="myform">
<input type="text" name="name" id="" autocomplete="off" placeholder="Name" required><br>
<input type="email" name="email" id="" autocomplete="off" placeholder="E-mail" required><br>
<textarea name="message" id="" cols="30" rows="10" placeholder="Type Your Message" required></textarea><br>
<button type="submit" id="btn" onclick="form_success()">Send</button>
<p id="thank-you-message">Thank you for contacting us. We will be in touch with you soon.</p>
</form>

Receiving PHP contact form error (Please complete the form and try again. )

I am creating a contact form with 5 fields which will email the input details to a set e-mail but when the form is submitted i,m receiving error! Please complete the form and try again. here is php code, js and htm form.
Any help would be much appreciated.
html Form:
<form id="contact-form" action="mail.php" method="post">
<div class="single-input">
<input type="text" name="name" id="comment-name" placeholder="Enter your name">
</div>
<div class="single-input">
<input type="email" placeholder="Your email">
</div>
<div class="single-input">
<input type="text" name="phone" placeholder="Phone">
</div>
<div class="single-input">
<input type="text" name="subject" placeholder="Subject">
</div>
<div class="single-input textarea">
<textarea cols="3" name="message" rows="3" placeholder="Write your message here"></textarea>
</div>
<div class="single-input">
<button type="submit" class="cr-btn cr-btn--sm cr-btn--transparent cr-btn--icon"><span>send</span></button>
</div>
</form>
PHP Code:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$subject = trim($_POST["subject"]);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($subject) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "akcent.chester#gmail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Subject: $subject\n\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
js/ajax-mail.js file:
$(function() {
// Get the form.
var form = $('#contact-form');
// Get the messages div.
var formMessages = $('.form-message');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#contact-form input,#contact-form textarea').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
<?php // Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"]=="POST") {
// Get the form fields and remove whitespace.
$name=strip_tags(trim($_POST["name"]));
$name=str_replace(array("\r", "\n"), array(" ", " "), $name);
$email=filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone=trim($_POST["phone"]);
$subject=trim($_POST["subject"]);
$message=trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($subject) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient="example#gmail.com";
// Set the email subject.
$subject="New contact from $name";
// Build the email content.
$email_content="Name: $name\n";
$email_content .="Email: $email\n\n";
$email_content .="Phone: $phone\n\n";
$email_content .="Subject: $subject\n\n";
$email_content .="Message:\n$message\n";
// Build the email headers.
$email_headers="From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
}
else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
}
else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
<form id="#contact-form" action="mail.php" method="post">
<div class="single-input">
<input type="text" name="name" id="comment-name" placeholder="Enter your name">
</div>
<div class="single-input">
<input type="email" placeholder="Your email">
</div>
<div class="single-input">
<input type="text" name="phone" placeholder="Phone">
</div>
<div class="single-input">
<input type="text" name="subject" placeholder="Subject">
</div>
<div class="single-input textarea">
<textarea cols="3" name="message" rows="3" placeholder="Write your message here"></textarea>
</div>
<div class="single-input">
<button type="submit" class="cr-btn cr-btn--sm cr-btn--transparent cr-btn--icon"><span>send</span></button>
</div>
</form>
<div class="single-input">
<input type="email" placeholder="Your email">
</div>
This input element is missing a "name" attribute!

$error messate POST into div in index.php

This is my first question on this site however I have been here millions of times looking for answer and I hope you can help me out this time as I wasn't able to figure it out myself.
I am not very skilled when it comes to coding but was hoping to amend the php contact form I have found online (it's free), the form itself is worki9ng but what I am struggling with is to set the errors to be printed on the main page where the form is, at them moment the yare displayed on the contact.php form which is where the php code is and I would like it all displayed in a div for example on index.php just under the form.
my contact.php
<?php
if (isset($_POST['submit'])) {}
$sendTo = "email address";
$subject = "msg content";
$headers = 'From: email address' . "\r\n";
$name = #$_POST['name'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'thank you';
$errorMessage = 'Please fill all the fields';
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "----------------------------------------";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Email: $email \n Message: $message";
if (isset($data->success) AND $data->success==true) {
mail($sendTo, $subject, $emailText, $headers);
$responseArray = $okMessage;
}
else
{
//verification failed
$responseArray = $errorMessage;
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray;
}
?>
<form method="post" name="contactform" action="contact.php" >
<div class="field half first">
<label for="name">name</label>
<input type="text" name="name" id="name" placeholder="name" />
</div>
<div class="field half">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="email#email.com" />
</div>
<div class="field">
<label for="message">message</label>
<textarea name="message" id="msg" rows="4" placeholder="type your message here"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="----------------------------------"></div>
<ul class="actions">
<li><input type="submit" value="send" class="special" /></li>
<li><input type="reset" value="reset pola" /></li>
</ul>
I have tried to use $_POST and $_GET to echo responseArray but I can't figure it out...
Is anyone able to provide a code I would have to use to display $okMessage and $errorMessage on index.php please?
Many thanks for all help

php mail with .js validation -> can't see any mistakes

I got this piece of code from a free template and I followed all the instructions that came with it, everything seems fine but mail doesn't go trough.
HTML:
<!--Start Contact form -->
<form name="enq" method="post" action="email/" onsubmit="return validation();">
<fieldset>
<input type="text" name="name" id="name" value="" class="input-block-level" placeholder="Name.." />
<input type="text" name="email" id="email" value="" class="input-block-level" placeholder="Email.." />
<textarea rows="11" name="message" id="message" class="input-block-level" placeholder="Message.."></textarea>
<div class="actions">
<input type="submit" value="Send!" name="submit" id="submitButton" class="btn btn-info pull-right" title="Send!" />
</div>
</fieldset>
</form>
<!--End Contact form -->
PHP
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="email#sample.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
header("Location:../contact.php?msg=Successful Submission! Thankyou for contacting us.");
else
header("Location:../contact.php?msg=Error To send Email !");
//contact:-your-email#your-domain.com
}
?>
JavaScript
function validation()
{
var contactname=document.enq.name.value;
var name_exp=/^[A-Za-z\s]+$/;
if(contactname=='')
{
alert("Name Field Should Not Be Empty!");
document.enq.name.focus();
return false;
}
else if(!contactname.match(name_exp))
{
alert("Invalid Name field!");
document.enq.name.focus();
return false;
}
var email=document.enq.email.value;
//var email_exp=/^[A-Za-z0-9\.-_\$]+#[A-Za-z]+\.[a-z]{2,4}$/;
var email_exp=/^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if(email=='')
{
alert("Please Enter Email-Id!");
document.enq.email.focus();
return false;
}
else if(!email.match(email_exp))
{
alert("Invalid Email ID !");
document.enq.email.focus();
return false;
}
var message=document.enq.message.value;
if(message=='')
{
alert("Query Field Should Not Be Empty!");
document.enq.message.focus();
return false;
}
return true;
}
I don't get any errors but mail doesn't simply go trough, checked spam etc.
I hope you changed
$to="email#sample.com";
to your actual e-mail.. I can't see anything else.
Seems it was due to webhost(mailserver). Works like a charm on another webhost.

event.preventDefault(); not working when submitting form

I am trying to put the result from a submitted form in to a div instead of opening it inside a new window. The problem is that my event.preventDefault(); doesn't seem to be working and I don't understand why. The result, after I hit the submit button is always to open the contact-form-handler.php, which is the script file.
Here is the code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
CONTACT FORM:
<form class="form-container" id="contactForm" method="post" action="contact-form-handler.php">
<div class="form-title">Full Name:</div>
<input class="form-field" type="text" name="name" /><br />
<div class="form-title">Email Address:</div>
<input class="form-field" type="text" name="email" /><br />
<div class="form-title">Phone Number:</div>
<input class="form-field" type="text" name="phone" /><br />
<div class="form-title">Message:</div>
<textarea class="form-field" rows="8" cols="34" name="message"></textarea><br />
<div id="contactResponse"></div>
<div class="submit-container">
<button type="submit" class="submit-button">Send</button>
</div>
</form>
SCRIPT CODE:
<script type="text/javascript">
$("#contactForm").submit(function(event)
{
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
name_value = $form.find( 'input[name="name"]' ).val(),
email_value = $form.find( 'input[name="email"]' ).val(),
phone_value = $form.find( 'input[name="phone"]' ).val(),
message_value = $form.find( 'textarea[name="message"]' ).val();
/* Send the data using post */
var posting = $.post( "contact-form-handler.php", {
name: name_value,
email: email_value,
phone: phone_value,
message: message_value
});
posting.done(function( data )
{
/* Put the results in a div */
$( "#contactResponse" ).html(data);
/* Change the button text. */
$submit.text('Sent, Thank you');
/* Disable the button. */
$submit.attr("disabled", true);
});
});
</script>
PHP CODE:
<?php
$myemail = 'mymail#mail.com';//<-----Put Your email address here.
$name = $_POST['name'];
$phone = $_POST['phone'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "Contact Form Emocool Website ".
" Here are the details:\n Name: $name \n Telefono: $phone \n Email: $email_address \n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
if(mail($to,$email_subject,$email_body,$headers))
{
echo "Thank you for contacting us";
}
//redirect to the 'thank you' page
else
{
echo "Sorry, there has been an error";
}
?>
So the problem is when I hit the submit button, instead of the result showing inside the #contactResponse div, it is showing inside new page of the script contact-form-handler.php
Any suggestions why this is not working?
My best guess is that you are adding your #contactForm submit listener before the form is actually rendered. Try wrapping your jQuery in $(document).ready(function () {});
I don't see any other issues.
Using <script type="text/javascript"> , your script will not work, replace <script type="text/javascript"> with <script language="javascript">, It will work correctly. But language="javascript" is deprecated in favor of type="text/javascript". keep in mind you put the code $(document).ready(function(){ //code to be implemented// });
Anyhow your script will work by replacing type="text/javascript" with language="javascript"

Categories