I have a contact form on my website, I’m trying to use AJAX to make it so that only part of the page is refreshed when the form is filled out (rather than the whole thing). Is this the way to accomplish this feat?
(put this in the head)
<script>
function contactOwner() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("contact_form").innerHTML = this.responseText;
}
};
xmlhttp.open("POST", "contact_owner.php?id=<?=$propertyID?>&email=attempt", true);
xmlhttp.send();
}
</script>
(then in the body)
<form onsubmit="contactOwner()">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control form-control-sm" id="name" name="name" placeholder="Name" value="<?=$_SESSION['name']?>">
</div>
<div class="form-group">
<label for="email">Your Email Address</label>
<input type="email" class="form-control form-control-sm" id="email" name="email" placeholder="Email" value="<?=$_SESSION['email']?>">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="message">Your Message</label>
<textarea class="form-control form-control-sm" id="message" name="message" rows="5" placegolder="Message"></textarea>
</div>
<button type="submit" class="btn btn-primary btn-block"><i class="fa fa-envelope-o" aria-hidden="true"></i> Contact Owner</button>
</form>
(then in the PHP page)
<?php
if ($_GET["email"] == "attempt"){
$headers = "From: ". stripslashes($_POST['email'])."/r/n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$to= $row['userEmail'];
$messageSubject='VRBO-Shores Contact Owner Form';
$email='';
$body='';
$name = $_POST['name'];
if ($_POST){
$email=stripslashes($_POST['email']);
$body=stripslashes($_POST['message']);
$msgbody = "<html><body>";
$msgbody .= "<table><tr><th>Name</th><td>".$name."</td></tr>";
$msgbody .= "<tr><th>Email</th><td>".$email."</td></tr>";
$msgbody .= "<tr><th>Body</th><td>".$body."</td></tr></table>";
$msgbody .= "</body></html>";
if ($email && $body){
if (mail($to,$messageSubject,$msgbody,$headers)) {
print ('<div class="alert alert-success" role="alert">Your message has been sent off to the owner.</div>');
}else{ // the messages could not be sent
print ('<div class="alert alert-danger" role="alert">Sorry, we are having problems with our server.</div>');
}
}
}
}
?>