Im building a contact form using php and ajax with following code:
HTML:
<head>
<script src="js/app.js"></script>
</head>
<body>
<form id="ajax-contact" method="post" action="php/mailer.php">
<input type="text" id="name" name="name" required>
<input type="text" id="email" name="email" required>
<textarea id="message" name="message" required></textarea>
<input class="submit" type="submit" value="Send">
</form>
<div id="form-messages">
</div>
</body>
AJAX:
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
});
$(form).submit(function(event) {
event.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').val('');
$('#email').val('');
$('#message').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
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("","
"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "mailreceiver@example.com";
$subject = "New contact from $name";
$email_content = "Name: $name
";
$email_content .= "Email: $email
";
$email_content .= "Message:
$message
";
$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 "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.";
}
?>
In Ajax on action I load the php mailer file to send the mail to my current mail address BUT I want to do this in the background the page shouldn't be loaded since I'm using ajax... I want to stay on the html page of the form without redirecting to that php page for sending that mail and just display succes or failure in the div:form-messages.
What am I missing here?