Reputation: 89
I'm having some strange issues when trying to submit a form via ajax. For the $(form).on('submit'), this works yet it redirects to the email.php script even with preventDefault() but I get my values passed and the email is sent.
The $('#submit').on('click') shows in the request payload that it's being sent, however the email gets fired off resulting in no content, but the page does not reload.
$(function(){
var form = document.getElementById('ajax-contact');
// $(form).on('sumbit', function(e){ // This works but redirects to the email processing page.
$('#submit').on('click', function(e){
var data = {
name: $("input[name='name']").val(),
email: $("input[name='email']").val(),
message: $("input[name='message']").val()
};
$.ajax({
type: "POST",
url: "/api/email.php",
contentType: "application/json",
data: JSON.stringify({ "email": $("#email").val(), "name": $("#name").val(), "message": $("#message").val() }),
beforeSend: function(){
$("#submit").attr("value","Processing your request...");
},
success: function(data){
$("#submit").attr("value","Thank you, I will get back to you as soon as possible.");
},
error: function(xhr, textStatus){
if(xhr.status === 404) {
$('#submit').attr("value","There was an ERROR processing your request");
}
}
});
e.preventDefault();
});
});
Here is the php script.
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
echo 'Email Processed';
$recipient = '[email protected]';
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$msg_body = "Name: " . $name . "Email: " . $email . 'Message: ' . $msg;
mail($recipient,'Message from: ' . $name , $msg_body);
} else {
return;
}
?>
Upvotes: 2
Views: 97
Reputation: 91734
You are not sending key - value pairs to the server but one single string:
data: JSON.stringify({ "email": $("#email").val(), "name": $("#name").val(), "message": $("#message").val() }),
should be:
data: { "email": $("#email").val(), "name": $("#name").val(), "message": $("#message").val() },
or:
// you already generated an object with the data
data: data,
You actually can send a string but than you would need to read the raw input.
And you really should catch the form submit in case someone does not push the button but uses the enter key instead:
$(form).on('submit', function(e){
^^^^^^ small typo here
e.preventDefault();
Upvotes: 1