So this is the second website I made.
I have never worked with PHP or Ajax before, so this is the very first time. However, when you try to use the RSVP form, it validates the data, but the submit button does not work. Now I can't seem to figure out if its because of PHP or Ajax. And why?
I had the PHP form included but not Ajax. The form submitted but caused an error that's included in the PHP file. Now that I've included the Ajax file it does not send the form data at all.
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);
$events = ($_POST["events"]);
$guests = ($_POST["guests"]);
$guestinfo = trim($_POST["guestinfo"]);
$message = trim($_POST["message"]);
if (empty($name) OR empty($events) OR empty($guests) OR empty($guestinfo) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("HTTP/1.0 404 Not Found?");
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "danielwedsnicole@gmail.com";
$subject = "RSVP from $name";
$email_content = "Name: $namenn";
$email_content .= "Email: $emailnn";
$email_content .= "Events: $eventsnn";
$email_content .= "Guests: $guestsnn";
$email_content .= "Guests details: $guestinfonn";
$email_content .= "Message:n$messagenn";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
header('HTTP/1.0 200 OK');
echo "Thank You! Your message has been sent.";
} else {
header('HTTP/1.0 500 Internal Server Error');
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
header('HTTP/1.0 403 Forbidden');
echo "There was a problem with your submission, please try again.";
}
AJAX
$(function() {
var form = $('#rsvp-form');
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('alert alert-danger');
$(formMessages).addClass('alert alert-success');
$(formMessages).text(response);
$('#cname').val('');
$('#cemail').val('');
$('#cevents').val('');
$('#cguests').val('');
$('#cguestinfo').val('');
$('#cmessage').val('');
})
.fail(function(data) {
$(formMessages).removeClass('alert alert-success');
$(formMessages).addClass('alert alert-danger');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
Aucun commentaire:
Enregistrer un commentaire