I have a JS script that validates data from a contact form. I need, once the entered values have been validated, to send the data to the PHP file that will send the email. The PHP works correctly (verified without the JS pre-submission validation process)
The JS:
// GET DATA
const nameInput = document.querySelector("#name");
const email = document.querySelector("#email");
const phone = document.querySelector("#phone");
const message = document.querySelector("#message");
//......
function sendEmail(){
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: {
'nameInput': nameInput,
'email': email,
'phone' : phone,
'message' : message
},
});
}
The PHP:
<?php
$toEmail = "[email protected]";
$subject = "Message from Whatever"
$mailHeaders = "From: " . $_POST["nameInput"] . "<". $_POST["email"] .">\r\n";
if(mail($toEmail, $_POST["subject"], $_POST["message"], $mailHeaders)) {
print "<p class='success'>Message Sent</p>";
} else {
print "<p class='Error'>Error! try again</p>";
}
?>
The console says:
Uncaught ReferenceError: ajax is not defined at sendEmail (script.js:57:5)
57 $.ajax({
CodePudding user response:
Why not use the default form submit functionality:
<form method="POST" action="path/to/sendmail.php">
<label for="nameInput">Name:</label>
<input type="text" id="nameInput" name="nameInput">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
...
<input type="submit" value="Submit">
</form>
CodePudding user response:
It seems, the jQuery library missing on that page. Make sure, that you load jQuery, before your javascript function sendEmail() is called.