0

I am using Js and PHP, so basically I would like form submissions to be sent via emails with out the page to reload which it is not working. Any help would be great thanks.

This is just a simple form where you submitted and the input data appears below where it should be sent via email as well.

<form id="myForm" method="post">
    Name:    <input name="name" id="name" type="text" /><br />

    <input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
  </form>
  <br/>
  Your data will display below..... <br />
  ==============================<br />
  <div id="results">
     <!-- All data will display here  -->
  </div>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function SubmitFormData() {
    var name = $("#name").val();
    $.post("./submit.php", { name: name },
       function(data) {
         $('#results').html(data);
         $('#myForm')[0].reset();
       });
}
</script>```



Here another file on form process.
<?php

if( $_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = $_POST['name'];

    echo $name;

    $to = 'name@name.com';
    $subject = " Test Enquiries";

    // Always set content-type when sending HTML email
    $headers .= "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // More headers
    $headers .= 'From: domain@domain.com' . "\r\n";

    // Email body content
    $message = "
        <p><strong>Name:</strong> <span>{$name}</span></p>
    ";

    mail($to,$subject,$message,$headers);

    if (mail ($to, $subject, $message, $headers)) 
        { 
            echo '<p>Your message has been sent!</p>';
        } 
    else 
        { 
            echo '<p>Something went wrong, go back and try again!</p>'; 
    }

}
?>

  • Remove the inline `onclick` for your input (it's bad practice), then use `$('#myForm').on('submit', SubmitFormData);`. At the end of the `SubmitFormData` function `return false;` to prevent the regular form submission. –  May 21 '20 at 18:37
  • See [How to prevent default event handling in an onclick method?](https://stackoverflow.com/questions/7056669/how-to-prevent-default-event-handling-in-an-onclick-method) – Ed Lucas May 21 '20 at 19:16
  • Thanks for the help but I still need the data to be sent through by emails. which is the main problem for me. – Tom Irving May 22 '20 at 08:27

0 Answers0