javascript - Ajax request form submit issue -
i'm having strange issues when trying submit form via ajax. $(form).on('submit'), works yet redirects email.php script preventdefault() values passed , email sent.
the $('#submit').on('click') shows in request payload it's being sent, email gets fired off resulting in no content, page not reload.
$(function(){ var form = document.getelementbyid('ajax-contact'); // $(form).on('sumbit', function(e){ // works redirects 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 request..."); }, success: function(data){ $("#submit").attr("value","thank you, possible."); }, error: function(xhr, textstatus){ if(xhr.status === 404) { $('#submit').attr("value","there error processing request"); } } }); e.preventdefault(); }); });
here php script.
<?php if($_server['request_method'] === 'post') { echo 'email processed'; $recipient = 'pete.robie@gmail.com'; $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; } ?>
you not sending key - value pairs server 1 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:
// generated object data data: data,
you can send string need read raw input.
and should catch form submit in case not push button uses enter key instead:
$(form).on('submit', function(e){ ^^^^^^ small typo here e.preventdefault();
Comments
Post a Comment