0

I originally built the form using this tutorial but now I need to add a checkbox for signing up to a newsletter. I've tried several fixes I have found already but none seem to be working correctly, and I'm quite new to PHP,AJAX,jQuery. It's been super frustrating :/

Here's the HTML:

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

The js:

$(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) {
	// Stop the browser from submitting the form.
	e.preventDefault();

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

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

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

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

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

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

});

});

And the PHP:

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
			$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.";
}

What Can I do here to make it process the checkbox data?

1
  • its submitting. But only if the checkbox is checked. Commented Oct 13, 2015 at 11:35

2 Answers 2

1

Yes. its submitting only when its checked.

You can change you code

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

to

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

EDIT: Change the line $subscribe = "Subscribe: $subscribe\n"; will be $email_content .= "Subscribe: $subscribe\n"

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for this, it has helped! I also figured out why it wasn't showing up in the email, I had made an error using "$subscribe" where it should've said "$email_content".
You have assigned the variable $subscribe twice. The change was for the first time you assigned it.
You need to check if the value of $_POST["subscribe"] is coming to your php code. use isset() function. Check code in my answer below
also, the line $subscribe = "Subscribe: $subscribe\n"; will be $email_content .= "Subscribe: $subscribe\n";
I saw my error just as you guys posted, thank you for pointing it out. Can't believe I missed it before now.
0

You need to check if the value of $_POST["subscribe"] is coming to your php code. use isset() function to do so...

Edited your script, should work fine now.

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
			$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.";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.