Adding line breaks in form submission

josephgregorydesign
josephgregorydesign used Ask the Experts™
on
I'm trying to add line breaks between name, phone, company, etc. in the email that is sent.  I tried editing a few things in the "var dataString" line, but it would only break the form.


/* =================================
===  CONTACT FORM          ====
=================================== */
$("#contact").submit(function (e) {
    e.preventDefault();
    var name = $("#name").val();
    var company = $("#company").val();
    var phone = $("#phone").val();
    var email = $("#email").val();
    var subject = $("#subject").val();
    var message = $("#message").val();
    var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + 'name=' + name + 'company=' + company + 'phone=' + phone + 'email=' + email + '&message=' + message;
	

 
    function isValidEmail(emailAddress) {
        var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
        return pattern.test(emailAddress);
    };

    if (isValidEmail(email) && (message.length > 1) && (name.length > 1)) {
        $.ajax({
            type: "POST",
            url: "subscribe/sendmail.php",
            data: dataString,
            success: function () {
                $('.success').fadeIn(1000);
                $('.error').fadeOut(500);
            }
        });
    } else {
        $('.error').fadeIn(1000);
        $('.success').fadeOut(500);
    }

    return false;
});

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2016

Commented:
Please post the rest of the puzzle.  We need to see the semantic markup (HTML) and the PHP script that resides at url: "subscribe/sendmail.php", thanks.

Author

Commented:
This is sendmail.php

<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['subject']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
 
  // detect & prevent header injections
  $test = "/(content-type|bcc:|cc:|to:)/i";
  foreach ( $_POST as $key => $val ) {
    if ( preg_match( $test, $val ) ) {
      exit;
    }
  }

$headers = 'From: ' . $_POST["name"] . '<' . $_POST["email"] . '>' . "\r\n" .
    'Reply-To: ' . $_POST["email"] . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

  //
  mail( "gregory@josephgregorydesign.com", $_POST['subject'], $_POST['message'], $headers );
 
}
?>

Open in new window

Author

Commented:
And this is the form code from the html file.

<!-- FORM -->
				<form class="contact-form" id="contact" role="form">

					<!-- IF MAIL SENT SUCCESSFULLY -->
					<h4 class="success">
						<i class="icon_check"></i> Your message has been sent successfully.
					</h4>

					<!-- IF MAIL SENDING UNSUCCESSFULL -->
					<h4 class="error">
						<i class="icon_error-circle_alt"></i> E-mail must be valid and message must be longer than 1 character.
					</h4>

					<div class="col-md-6">
						<input class="form-control input-box" id="name" name="name" placeholder="Your Name*" type="text">
					</div>

					<div class="col-md-6">
						<input class="form-control input-box" id="company" name="company" placeholder="Your Company*" type="text">
					</div>
                    
                    <div class="col-md-6">
						<input class="form-control input-box" id="phone" type="text" name="phone" placeholder="Your Phone Number*">
					</div>

					<div class="col-md-6">
						<input class="form-control input-box" id="email" type="email" name="email" placeholder="Your Email*">
					</div>
                    

					<div class="col-md-12">
						<input class="form-control input-box" id="subject" name="subject" placeholder="Subject" type="text">
						<textarea class="form-control textarea-box" id="message" rows="8" placeholder="Message"></textarea>
					</div>

					<button class="btn btn-primary standard-button2 ladda-button" type="submit" id="submit" name="submit" data-style="expand-left">Send Message</button>

				</form>
				<!-- /END FORM -->

Open in new window

Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Most Valuable Expert 2011
Top Expert 2016

Commented:
Thanks for posting that - very helpful!

I think you can add a text/plain header.  I'll try to test that idea later and I'll post back with the results.
http://php.net/manual/en/function.mail.php#108368

If that does not work, an HTML <br> tag might be inserted, or single line breaks, indicated by PHP_EOL, could be doubled up to make a blank line.
greetings josephgregorydesign, , your problem is in this LINE -
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + 'name=' + name + 'company=' + company + 'phone=' + phone + 'email=' + email + '&message=' + message;

Open in new window


because you DO NOT convert the text (and it's punctuation and symbols) of the inputs (especially the message) to URL safe characters , as the line breaks are NOT safe to use in the URL.

you use the Jquery AJAX as -
$.ajax({ type: "POST",
   url: "subscribe/sendmail.php",
   data: dataString,

so the "String" you use in the "data" in not correctly formatted, since Jquery Ajax will automatically format the URL strings for you, you should use it's "data" as an Object, not a string , make an object like this -
var urlObj = {
  name: name, 
  email: email, 
  subject: subject + 'name=' + name + 'company=' + company + 'phone=' + phone + 'email=' + email, 
  message:message
}
// other code goes here
$.ajax({
  type: "POST",
  url: "subscribe/sendmail.php",
  data: urlObj,
  success: function () {
  $('.success').fadeIn(1000);
  $('.error').fadeOut(500);
  }
  });

Open in new window

you should look at the Jquery AJAX API page for additional info, if this is not clear.
  ask questions if I can help more. AND I do not think you can have line breaks in the subject line?
It is generally  "Bad Practice" to have a long subject line in an email, many phone emails will not even show a long subject line.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Well, it looks like we need to start over with a working script!  This one will not send any email at all.  I'll try to strip out all the extraneous stuff and just show the SSCCE.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Here is the code I used and some screen shots to show that the multi-line message comes through correctly.  The HTML and PHP work together in a way that makes sense.  I think it's the JavaScript that is causing the problem, so you should probably pursue Slick812's line of inquiry to get your answer.
<?php // demo/temp_joseph.php
/**
 * https://www.experts-exchange.com/questions/28939579/Adding-line-breaks-in-form-submission.html
 */
error_reporting(E_ALL);


// ADD YOUR SANITY CHECKS HERE
if (!empty($_POST))
{
    // USE COMPLETELY DUMMY DATA EXCEPT FOR THE HTML TEXTAREA
    $to = 'ray.paseur@gmail.com';
    $su = 'Test from E-E 28939579';
    $hd = NULL;
    $hd .= "From: Ray <Ray.Paseur@Iconoun.com>\r\n";
    $hd .= "Reply-To: Ray.Paseur@Iconoun.com\r\n";
    $tx = $_POST['msg'];

    mail($to, $su, $tx, $hd);
}
?>
<form method="post">
<textarea name="msg" rows="8" placeholder="Message"></textarea>
<br>
<button type="submit">Send Message</button>
</form>

Open in new window

FormInbox shows message arrived Message has correct line spacing

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial