#javascript #php #html #jquery #forms
#javascript #php #HTML #jquery #формы
Вопрос:
Я пытаюсь отправить электронное письмо самому себе с текстом, который был введен в текстовое поле.
<form class="form align-center" id="mailchimp">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="newsletter-label font-alt">
Stay informed with our newsletter
</div>
<div class="mb-20">
<input placeholder="Enter Your Email" class="newsletter-field form-control input-md round mb-xs-10"
name="emaill" type="email" pattern=".{5,100}" required aria-required="true">
<button type="submit" aria-controls="subscribe-result" id="submit_btnn"
class="btn btn-mod btn-medium btn-round mb-xs-10">
Subscribe
</button>
</div>
<div class="form-tip">
<i class="fa fa-info-circle"></i> Please trust us, we will never send you spam
</div>
<div id="subscribe-result" role="region" aria-live="polite" aria-atomic="true"></div>
После этого я перехватываю его в Js
$(document).ready(function(){
$("#submit_btnn").click(function(){
//get input field values
var user_email = $('input[name=emaill]').val();
//simple validation at client's end
var proceed = true;
//we simply change border color to red if empty field using .css()
if (user_email == "") {
$('input[name=email]').css('border-color', '#e41919');
proceed = false;
}
//everything looks good! proceed...
if (proceed) {
//data to be sent to server
post_data = {
'userEmail': user_email
};
console.log(post_data);
//Ajax post data to server
$.post('nieuwsbrief.php', post_data, function(response){
//load json data from server and output message
if (response.type == 'error') {
output = '<div class="error">' response.text '</div>';
}
else {
output = '<div class="success">' response.text '</div>';
}
$("#subscribe-result").hide().html(output).slideDown();
}, 'json');
}
return false;
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function(){
$("#contact_form input, #contact_form textarea").css('border-color', '');
$("#subscribe-result").slideUp();
});
});
После этого я хочу использовать сообщение Ajax для отправки его в мой php-файл
<?php
if($_POST)
{
echo '<script>console.log($_POST["userEmail"])</script>';
$to_Email = "mathias@wizewolf.com"; //Replace with recipient email address
$subject = 'Message from website '.$_SERVER['SERVER_NAME']; //Subject line for emails
echo '<script>console.log(to_Email)</script>';
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userEmail"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = "d";
$user_Message = str_replace("amp;#39;", "'", $user_Message);
$user_Message = str_replace("amp;#39;", "'", $user_Message);
//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "rn" .
'Reply-To: '.$user_Email.'' . "rn" .
'X-Mailer: PHP/' . phpversion();
$sentMail = @mail($to_Email, $subject, $user_Message . "rnn" .'-- '.$user_Name. "rn" .'-- '.$user_Email, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .'! Thank you for your email'));
die($output);
}
}
?>
С помощью журнала консоли я обнаружил, что до начала файла PHP все работает. После этого … не так много. Все советы и информация приветствуются.
Комментарии:
1. в php, с которым вы не выполняете отладку
console.log
(это нарушает ваш ответ json), удалите их2. В тот момент, когда вы создаете вывод (echo, die и т. Д.) С помощью PHP, Он отправляется обратно в вашу функцию Ajax. Поскольку это завершает функцию обратного вызова, любой другой вывод вашего PHP-скрипта игнорируется. Поэтому не отправляйте выходные данные, пока ваш PHP-скрипт не выполнит свою работу. На заметку: не используйте переменные внутри одинарных кавычек. PHP обрабатывает их как обычный текст. Используйте двойные кавычки или конкатенацию строк
Ответ №1:
Вместо использования jQuery и PHP, вы могли бы использовать STMP.js . Я не знаю, как ответить на этот вопрос с помощью jQuery или PHP, но я знаю, как отправлять электронные письма с помощью SMTP. Я привел пример на JSFiddle ниже. Но это может не сработать на JSFiddle по соображениям безопасности.
JSFiddle
https://jsfiddle.net/Yeet45687564/9prs4j2a/21/
// the javascript code below is also found on JSFiddle
let subject;
let body;
function setValues() {
// sets the values of the subject and body
subject = document.getElementById("emailSubject").value;
body = document.getElementById("emailBody").value;
}
function send() {
setValues();
// sends the email
Email.send({
Host: "smtp.gmail.com",
Username: "<sender's email address>",
Password: "<your email password>",
To: "<recipient's email address>",
From: "<sender’s email address>",
Subject: subject,
Body: body,
}).then(
// displays a message if the email was sent
message => alert("Your Email was sent.")
);
}
Если вы не можете заставить это работать, в Pepipost есть руководство по SMTP.
https://pepipost.com/tutorials/how-to-send-emails-with-javascript/
Но использование SMTP может быть огромной проблемой безопасности. Любой, кто использует элемент inspect на вашем веб-сайте, сможет получить ваш пароль электронной почты, если только вы не сможете запретить им проверять его и просматривать источник страницы.