When the user clicks on the submit button I need: (1) The form data to be sent to me via email using PHP, without refreshing the page. (2) A thank you message to appear next to the form using Ajax.
I've got most of it working. I'm not to sure what coding I need to make the page NOT refresh as the PHP script is sending the form data to me via email. Also, once the PHP script is done running, how do I get the Ajax code to run? I've done a ton of research and have found a lot of people use jQuery to resolve this issue. However, I am not using jQuery for this just JavaScript. I know I am close, but need some help. Here is my code thus far:
PHP - Just sends the form data to me via email:
<?php
$persons_name = $_POST['fname'];
$email_address = $_POST['email'];
$comments_questions = $_POST['moreinfo'];
$to = 'fireplace_tea@yahoo.com';
$subject = 'Email - JulesMyers.com';
$msg = "$persons_name has sent an email.
" .
"You can reply to $persons_name at: $email_address
" .
"Question or Comment: $comments_questions
";
mail($to, $subject, $msg, 'From: ' . $email_address);
?>
HTML Form:
<form id="contactMe" method="post" action="contact.php">
<input type="text" class="inputElement initialColor" name="fname" id="fname">
<input type="text" class="inputElement initialColor" name="email" id="email">
<textarea rows="6" class="inputElement" name="moreinfo" id="moreinfo"> </textarea>
<input type="submit" class="sendButton" id="submitbutton" value="Send">
</form>
<div class="errormsg"></div>
<div class="formsent"></div>
Ajax: I have the Ajax working when I click the formsent div, but I need it to run after the PHP script does. Is there an event I can listen for?
(function() {
var httpRequest;
var b = document.querySelector('.formsent');
b.onclick = function() { makeRequest('thanks.txt'); };
function makeRequest(url)
{
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('POST', url);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === 4)
{
if (httpRequest.status === 200)
{
/*alert(httpRequest.responseText);*/
b.innerHTML = httpRequest.responseText;
}
}
}
})();
Thanks for any help. :)