Adding line breaks in form submission

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

josephgregorydesignAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
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.
josephgregorydesignAuthor 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

josephgregorydesignAuthor 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

Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Ray PaseurCommented:
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.
Slick812Commented:
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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
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.
Ray PaseurCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.