javascript - Page updates, when I try to send mail-foem data by using ajax+php
I am trying to send data by using ajax technology. I made an ajax_form.js file, that responsible for this function:
$(document).ready(function(){
var name = $("#name").val();
var email = $("email").val();
var message = $("message").val();
$("#push").submit(function(e){ // $("#push") is a button
e.preventDefault();
$.ajax({
url: "../send.php",
tpye: "POST",
cache: false,
data: { 'name': name, 'email': email, 'message': message },
dataType: 'html',
beforeSend: function(){
$("#push").prop("disabled",true);
},
succsess: function(data){
if(!data){
alert("???�???�???� ?????? ???�?????�?????� ???�?????�?�");
}
else{
$("#mail_form").trigger("reset");
alert(data);
}
$("push").prop("disabled", false);
},
})
})
})
I made the following script send.php, that contain variables and mail() function for sending:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = "=?utf-8?B?".base64_encode("?�?�???????� ?? ???�???�?�")."?=";
$headers = "From: $email\r\nReply to: $email\r\nContent-type: text/html; charset=utf-8\r\n";
$name = trim($name);
$name = trim($email);
if (isset($name) && isset($email) && isset($message)){
$success = mail("d.romanuk@mail.ru", $subject, $message, $headers);
echo $success;
}
ini_set("display_errors","1");
ini_set("display_startup_errors","1");
ini_set('error_reporting', E_ALL);
?>
Thisa is my html-form:
<form id="mail_form" class="mail__form" action="" id="send" method="post" name="form">
<label class="mail__label">
??????:
</label>
<br>
<input class="mail__input" id="name"type="text" name="name" placeholder="??????" required>
<br>
<label class="mail__label">
E-MAIL:
</label>
<br>
<input class="mail__input" type="mail" name="email" id="email" placeholder="example@gmail.com" required>
<br>
<label class="mail__label">
???????�?�?�?????�:
</label>
<br>
<textarea id="message" name="message" class="mail__message" required>
</textarea>
<br>
<button id="push" type="submit" class="mail__button">
???????�???�?????�
</button>
</form>
Here I have two problems:
1)When I click the button, the page is updated, and data from the mail form does not send; it should not update web page because I am using e.preventDefault()
2)And I suppose that my web-form doesn't work, because it should be alert()
after sending data
Answer
Solution:
Submit events are fired on form elements, but you are attaching your event listener to a button.
Move it to the form.
Source