0

I'd really appreciate your help here. I don't really know much about these things.

For my website's contact form: https://ma.rianahurta.do/#contact I'm trying to send a message with AJAX to avoid going to a different page and yet it still redirects to the message instead of printing it in the HTML.

Here's the HTML code

<form id="contactForm" action="contactengine.php" method="POST">
    <!-- Name Input -->
    <span class="fname fa fa-user"></span><input type="text" name="Name" id="Name" placeholder="name" required />
    <!-- Email Input -->
    <span class="femail fa fa-envelope"></span><input type="email" name="Email" id="Email" placeholder="email" required />
    <!-- Message textarea -->
    <span class="fmessage fa fa-align-left"></span><textarea required name="Message" id="Message" rows="4" cols="50" placeholder="message"></textarea>
    <!-- Submit Button -->
    <div class="row">
        <div class="col-md-8">
            <span class="fmessage fa fa-comments-o submitIcon"></span><input name="submit" class="button" type="submit" onClick="sendContact();" style="margin-left:0;margin-right:0" />
        </div>
    </div>
</form>

JS and AJAX inside the index.html:

function validateContact() {
  var valid = true;
  if (!$("#Name").val()) {
    valid = false;
  }
  if (!$("#Email").val()) {
    valid = false;
  }
  if (!$("#Email").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
    valid = false;
  }
  if (!$("#Message").val()) {
    valid = false;
  }
  return valid;
}

function sendContact() {
  var valid;
  valid = validateContact();
  if (valid) {
    jQuery.ajax({
      url: "contactengine.php",
      data: 'Name=' + $("#Name").val() + '&Email=' +
        $("#Email").val() + '&Message=' +
        $("#Message").val(),
      type: "POST",
      success: function(data) {
        $("#mail-status").html(data);
      },
      error: function() {}
    });
  }
}

And the php content (I changed the email on purpose):

$EmailFrom = Trim(stripslashes($_POST['Email']));
$EmailTo ="myemail@page.com";
$Subject = "Getting in Touch";
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
$Body = "";
$Body .= "Name: ";

$Body .= $Name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;

$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
if ($success){
    print "<p class='success'>Message sent.</p>";

} else {
    print "<p class='Error'>There was a problem, try again later.</p>";

}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Mary
  • 1
  • 1

0 Answers0