I am trying to have PHP inject rendered HTML into a page when a form is submitted. The form data is intercepted with AJAX and then sent to PHP.
Here Is the HTML form:
<span id="message-sent">
<form role="form" id="footer-form" name="contactform" method="post" action="email.php">
<div class="form-group has-feedback">
<label class="sr-only" for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name" required>
<i class="fa fa-user form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
<label class="sr-only" for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email" required>
<i class="fa fa-envelope form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
<label class="sr-only" for="message">Message</label>
<textarea class="form-control" rows="8" id="message" placeholder="Message" name="message" required></textarea>
<i class="fa fa-pencil form-control-feedback"></i>
</div>
<input type="submit" value="Send" class="btn btn-default">
</form>
</span>
This is the PHP:
<?php
// Added input sanitizing to prevent injection
// 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("","
"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
echo "There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "example@example.com";
// Set the email subject.
$subject = "Website Message from $name";
// Build the email content.
$email_content = "Name: $name
";
$email_content .= "Email: $email
";
$email_content .= "Message:
$message
";
// 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.
echo 'Thank you for sending us a message! We will get back to you ASAP!';
} else {
// Set a 500 (internal server error) response code.
echo "Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
echo "There was a problem with your submission, please try again.";
}
?>
I want the responses from the server to the page be in HTML and then be inserted into the original page via the AJAX. The AJAX fills the span in the html code. any ideas? Thanks!
You can do so:
$.ajax({
type: "POST",
url: "ajax.php",
data: {},
}).done(function( htmlFromAjax ) {
$("#ErrorMessageDiv").html(htmlFromAjax);
}).fail(function(jqXHR, textStatus) {
});