2015-10-13 3 views
0

Я изначально построил форму, используя this tutorial, но теперь мне нужно добавить флажок для подписки на рассылку. Я пробовал несколько исправлений, которые я нашел уже, но ни один из них не работает корректно, и я довольно новичок в PHP, AJAX, jQuery. Это было супер расстраивает:/AJAX не отправляет значения checkbox в PHP

Вот HTML:

<div id="form-messages"></div> 
 
<form class="green-txt" id="ajax-contact" method="post" action="mailer.php"> 
 
\t <div class="form-group"> 
 
\t  <label for="name">Name:</label> 
 
\t  <input type="text" class="form-control" id="name" name="name" placeholder="" required> 
 
\t </div> 
 
\t <div class="form-group"> 
 
\t  <label for="email">Email:</label> 
 
\t  <input type="email" class="form-control email-in" id="email" name="email" placeholder="" required> 
 
\t </div> 
 
\t <div class="form-group form-inline"> 
 
\t  <label for="subscribe">Subscribe: </label> 
 
\t  <input class="sub-btn" type="checkbox" id="subscribe" name="subscribe"> 
 
\t </div> 
 
\t <div class="row"> 
 
\t \t <div class="col-xs-6 col-xs-offset-3 col-sm-4 col-sm-offset-8 col-md-4 col-md-offset-8"> 
 
\t \t <button type="submit" class="btn-success btn btn-submit">Send</button> 
 
\t \t </div> 
 
\t </div> 
 
</form>

В ЯШ:

$(function() { 
 

 
// Get the form. 
 
var form = $('#ajax-contact'); 
 

 
// Get the messages div. 
 
var formMessages = $('#form-messages'); 
 

 
// Set up an event listener for the contact form. 
 
$(form).submit(function(e) { 
 
\t // Stop the browser from submitting the form. 
 
\t e.preventDefault(); 
 

 
\t // Serialize the form data. 
 
\t var dataString = $(form).serialize(); 
 

 
\t // Submit the form using AJAX. 
 
\t $.ajax({ 
 
\t \t type: 'POST', 
 
\t \t url: $(form).attr('action'), 
 
\t \t data: dataString 
 
\t }) 
 
\t .done(function(response) { 
 
\t \t // Make sure that the formMessages div has the 'success' class. 
 
\t \t $(formMessages).removeClass('error'); 
 
\t \t $(formMessages).addClass('success'); 
 

 
\t \t // Set the message text. 
 
\t \t $(formMessages).text(response); 
 

 
\t \t // Clear the form. 
 
\t \t $('#name').val(''); 
 
\t \t $('#email').val(''); 
 

 
\t }) 
 
\t .fail(function(data) { 
 
\t \t // Make sure that the formMessages div has the 'error' class. 
 
\t \t $(formMessages).removeClass('success'); 
 
\t \t $(formMessages).addClass('error'); 
 

 
\t \t // Set the message text. 
 
\t \t if (data.responseText !== '') { 
 
\t \t \t $(formMessages).text(data.responseText); 
 
\t \t } else { 
 
\t \t \t $(formMessages).text('Oops! An error occured and your message could not be sent.'); 
 
\t \t } 
 
\t }); 
 

 
}); 
 

 
});

И PHP:

// Only process POST reqeusts. 
 
if ($_SERVER["REQUEST_METHOD"] == "POST") { 
 
    // Get the form fields and remove whitespace. 
 
    $name = strip_tags(trim($_POST["name"])); 
 
\t \t \t $name = str_replace(array("\r","\n"),array(" "," "),$name); 
 
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL); 
 
    $subscribe = trim($_POST["subscribe"]); 
 

 

 
    // Check that data was sent to the mailer. 
 
    if (empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) { 
 
     // Set a 400 (bad request) response code and exit. 
 
     http_response_code(400); 
 
     echo "Oops! There was a problem with your submission. Please complete the form and try again."; 
 
     exit; 
 
    } 
 

 
    // Set the recipient email address. 
 
    // FIXME: Update this to your desired email address. 
 
    $recipient = ""; 
 

 
    // Set the email subject. 
 
    $subject = "UP News New Contact - $name"; 
 

 
    // Build the email content. 
 
    $email_content = "Name: $name\n"; 
 
    $email_content .= "Email: $email\n"; 
 
    $subscribe = "Subscribe: $subscribe\n"; 
 

 

 

 
    // Build the email headers. 
 
    $email_headers = "From: $name <$email>"; 
 

 
    // Send the email. 
 
    if (mail($recipient, $subject, $email_content, $email_headers)) { 
 
     // Set a 200 (okay) response code. 
 
     http_response_code(200); 
 
     echo "Thank You!"; 
 
    } else { 
 
     // Set a 500 (internal server error) response code. 
 
     http_response_code(500); 
 
     echo "Oops! Something went wrong and we couldn't send your message."; 
 
    } 
 

 
} else { 
 
    // Not a POST request, set a 403 (forbidden) response code. 
 
    http_response_code(403); 
 
    echo "There was a problem with your submission, please try again."; 
 
}

Что я могу сделать здесь, чтобы сделать его обрабатывать данные флажок?

+0

его подачи. Но только если флажок установлен. –

ответ

0

Да. его подача только при ее проверке.

Вы можете изменять код

$subscribe = trim($_POST["subscribe"]); 

к

$subscribe = isset($_POST["subscribe"]) ? 'Yes' : 'No' ; 

EDIT: Изменение строки $ подписаться = "Подписка на новости: $ подписываться \ п"; будет $ email_content. = "Подписаться: $ subscribe \ n"

+0

Спасибо за это, это помогло! Я также понял, почему он не появился в письме, я сделал ошибку, используя «$ subscribe», где он должен был сказать «$ email_content». – HMiller

+0

Вы назначили переменную $ subscribe дважды. Это изменение было впервые назначено вам. –

+0

Вам нужно проверить, подходит ли значение $ _POST ["subscribe"] к вашему php-коду. использовать isset() функция. Проверить код в моем ответе ниже –

0

Вам нужно проверить, подходит ли значение $ _POST ["subscribe"] к вашему php-коду. использование isset() функция для этого ...

Отредактируйте ваш скрипт, теперь он должен работать нормально.

// Only process POST reqeusts. 
 
if ($_SERVER["REQUEST_METHOD"] == "POST") { 
 
    // Get the form fields and remove whitespace. 
 
    $name = strip_tags(trim($_POST["name"])); 
 
\t \t \t $name = str_replace(array("\r","\n"),array(" "," "),$name); 
 
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL); 
 
    //$subscribe = trim($_POST["subscribe"]); 
 
    $subscribe = (isset($_POST["subscribe"]))?"Yes":"No"; 
 

 

 
    // Check that data was sent to the mailer. 
 
    if (empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) { 
 
     // Set a 400 (bad request) response code and exit. 
 
     http_response_code(400); 
 
     echo "Oops! There was a problem with your submission. Please complete the form and try again."; 
 
     exit; 
 
    } 
 

 
    // Set the recipient email address. 
 
    // FIXME: Update this to your desired email address. 
 
    $recipient = ""; 
 

 
    // Set the email subject. 
 
    $subject = "UP News New Contact - $name"; 
 

 
    // Build the email content. 
 
    $email_content = "Name: $name\n"; 
 
    $email_content .= "Email: $email\n"; 
 
    $subscribe = "Subscribe: $subscribe\n"; 
 

 

 

 
    // Build the email headers. 
 
    $email_headers = "From: $name <$email>"; 
 

 
    // Send the email. 
 
    if (mail($recipient, $subject, $email_content, $email_headers)) { 
 
     // Set a 200 (okay) response code. 
 
     http_response_code(200); 
 
     echo "Thank You!"; 
 
    } else { 
 
     // Set a 500 (internal server error) response code. 
 
     http_response_code(500); 
 
     echo "Oops! Something went wrong and we couldn't send your message."; 
 
    } 
 

 
} else { 
 
    // Not a POST request, set a 403 (forbidden) response code. 
 
    http_response_code(403); 
 
    echo "There was a problem with your submission, please try again."; 
 
}

Смежные вопросы