Before submit form in ajax print value and send mail
You can use the preventDefault()
method to prevent the form from submitting normally, and then use JavaScript to print the values and send the email using AJAX.
Here is an example:
<form id="myForm">
<!-- form fields here -->
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // prevent the form from submitting normally
// get the form values
var formData = new FormData(document.getElementById("myForm"));
var values = {};
formData.forEach(function(value, key) {
values[key] = value;
});
// print the values
console.log(values);
// send the email using AJAX
var xhr = new XMLHttpRequest();
xhr.open("POST", "your-email-script.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(JSON.stringify(values));
// you can also use jQuery's $.ajax method
// $.ajax({
// type: "POST",
// url: "your-email-script.php",
// data: values,
// success: function(data) {
// console.log(data);
// }
// });
});
</script>
In this example, we add an event listener to the form's submit
event. When the form is submitted, we prevent the default behavior using event.preventDefault()
. Then, we get the form values using FormData
and print them to the console.
Next, we send the email using AJAX by creating an XMLHttpRequest
object and setting its open
method to send a POST request to the email script. We also set the Content-Type
header to application/x-www-form-urlencoded
and send the form values as a JSON string using JSON.stringify()
.
You can also use jQuery's $.ajax
method to send the email, as shown in the commented-out code.
Make sure to replace your-email-script.php
with the actual URL of your email script.
Note that this code assumes that your email script is set up to receive the form values and send the email. You will need to modify the code to match your specific requirements.