Is this the way to use AJAX?

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>&nbsp;&nbsp;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>');
      }
	}
  }
}
?>

More or less.

You might want to edit the JS to handle other possible error conditions.

In PHP, you are printing the result but you might want to set headers and send a proper HTTP response code.

In the JS, unless I’m mistaken, you need to still send the POST variables with the send() function. This is typically done with a serialize function that converts the form data to a string for this purpose. jQuery has a serialize function, otherwise there are other techniques available.

See here for the POST example for setting request header and send().
Here is a non-jquery serializer function: https://plainjs.com/javascript/ajax/serialize-form-data-into-an-array-46/

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.