Link to home
Create AccountLog in
PHP

PHP

--

Questions

--

Followers

Top Experts

Avatar of David Schure
David Schure

Line Break Not Working

The line break is not working…

User generated image

I tried this…

if ($httpCode === 202) {
   echo "Your Email Has Been Sent!\n";
    echo "Thank You!";
} else {

 

AND THIS

if ($httpCode === 202) {
   echo "Your Email Has Been Sent!<br>";
    echo "Thank You!";
} else {

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of David SchureDavid Schure

ASKER

I tried this…

if ($httpCode === 202) {
   echo "Your Email Has Been Sent!\n";
    echo "Thank You!\n";
} else {

 

AND THIS

I tried this…

if ($httpCode === 202) {
   echo "Your Email Has Been Sent!\r\n";
    echo "Thank You!\r\n";
} else {


Avatar of Daniel Pineault (Microsoft MVP)Daniel Pineault (Microsoft MVP)🇨🇦

Is this an Ajax call? Controller action?  What type of response format are you assigning?  You're sure you're not needing to pass the message back as json and update the html of an element.

 

I think we need a little more context and/or the full procedure to review.


<?php
$text = "This is the first line.\nThis is the second line.";
echo nl2br($text);
?>

 

should work

 

if ($httpCode === 202) {
   echo "Your Email Has Been Sent!<br>";
    echo "Thank You!";
} else {


Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


The “Email sent” is on the sendgrid.php page..  it is the called via javascriprt…

 

<script>
document.addEventListener("DOMContentLoaded", async function () {
   const form = document.getElementById("custom-contact-form");
   
   const res = await fetch("csrf-token.php", { credentials: "same-origin" });
   
   if (res.ok) {
       const { token } = await res.json();
       const csrf_token = document.getElementById("csrf_token");
       csrf_token.value = token;
       csrf_token.defaultValue = token;
   }

   form.addEventListener("submit", async function (e) {
       e.preventDefault()

       const formData = new FormData(form);

       try {
           const response = await fetch("sendgrid.php", {
               method: "POST",
               body: formData,
           });

           const text = await response.text();
           showPopup(text);
           form.reset();
       } catch (error) {
           showPopup("An error occurred. Please try again.");
           console.error(error);
       }
   });

   function showPopup(message) {
       const existing = document.getElementById("popup-overlay");
       if (existing) existing.remove();

       const overlay = document.createElement("div");
       overlay.id = "popup-overlay";
       overlay.style.position = "fixed";
       overlay.style.top = 0;
       overlay.style.left = 0;
       overlay.style.width = "100%";
       overlay.style.height = "100%";
       overlay.style.background = "rgba(0,0,0,0.5)";
       overlay.style.display = "flex";
       overlay.style.alignItems = "center";
       overlay.style.justifyContent = "center";
       overlay.style.zIndex = 9999;

       const popup = document.createElement("div");
       popup.style.background = "#fff";
       popup.style.padding = "10px";
       popup.style.borderRadius = "8px";
       popup.style.maxWidth = "400px";
       popup.style.textAlign = "center";
        popup.style.color = "green";
        popup.style.boxShadow = "0 2px 10px rgba(0,0,0,0.3)";

       const msg = document.createElement("p");
       msg.style.marginTop = "15px";
        msg.style.color = "green"; 
        msg.style.fontSize = "18px";
        msg.style.fontweight = "900"; 
        msg.textContent = message;

       const button = document.createElement("button");
       button.textContent = "OK";
       button.style.marginBottom = "15px";
       button.style.color = "white";
        button.style.backgroundColor = "red";
        button.style.borderRadius = "5px";
        button.style.lineHeight = "20px";
        button.style.fontsize = "16px";
        button.style.fontweight = "700";
        button.onclick = () => overlay.remove();

       popup.appendChild(msg);
       popup.appendChild(button);
       overlay.appendChild(popup);
       document.body.appendChild(overlay);
   }
});    
   </script>

 

Hopefully this helps..


Hi David, this did not work..

$text = "This is the first line.\nThis is the second line.";
echo nl2br($text);


Hey David,

 

My guess is that your ‘response’ is being sanitized somewhere in transit. You're sending an HTML <br> tag, but that'll get switched out so instead of it keeping the <br> tag, it will change the arrow to HTML Entities, so you'll get this insteadl : &lt;br;&gt;

 

If you load up your page and then inspect your popup using the WebDev tools, you'll likely see that sanitised code.

 

In your code above, you're asking for text() from your fetch() response. Dump that to the console and see what you get:

 

const text = await response.text();
console.log(text);

Open in new window

 

If you're seeing the sanitised data, then take a look at your sendgrid.php page as that's where the problem is going to be

 


Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


FYI - calling nl2br at the server side won't fix the issue is the <br> tags are being sanitised


Avatar of gr8gonzogr8gonzo🇺🇸

That likely means that WHERE you're echo-ing is part of a template that is intended to be text-only. As a result, the <br> is being treated as text instead of HTML. You need to share more of the surrounding code.  


Hi..here is the sendgrid.php page.

session_start();
$allowed_domain = "davidschure.com";

if (empty($_SERVER['HTTP_ORIGIN']) && empty($_SERVER['HTTP_REFERER'])) {
   exit('No origin');
}

$origin = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'];

if (strpos($origin, $allowed_domain) === false) {
   http_response_code(403); // Forbidden
   exit('Forbidden');
}

// NEVER hardcode secrets. Put your API key in an env var or a file outside webroot.
$sendgridApiKey = getenv('SENDGRID_API_KEY');
if (!$sendgridApiKey) {
   http_response_code(500);
   error_log("SendGrid API key missing.");
   exit;
}

// CSRF check
$csrf_token = $_POST['csrf_token'];
if (
   empty($csrf_token) ||
   empty($_SESSION['csrf_token']) ||
   !hash_equals($_SESSION['csrf_token'], $csrf_token)
) {
   error_log("Bad CSRF {$csrf_token}" . print_r($_SESSION, true));
   die();
}

// If we get here it should be legit
$requestName = $_POST['name'] ?? '';
$requestPhone = $_POST['phone'] ?? '';
$requestEmail = $_POST['email'] ?? '';
$requestSubject = $_POST['subject'] ?? '';
$requestMessage = $_POST['message'] ?? '';

// Ignore empty values
if (empty($requestName) || (empty($requestEmail) && empty($requestPhone)) || empty($requestSubject) || empty($requestMessage)) die();


// Map your existing values:
$fromEmail   = 'info@davidschure.com';   // must be a verified sender/domain in SendGrid
$fromName    = 'David';
$toEmail     = 'info@davidschure.com';
$toName      = 'David';
$replyToMail = 'info@davidschure.com';
$replyToName = 'David';
$subject     = $requestSubject;
$htmlBody    = <<< EOT
<div>
 <div><b>From</b> {$requestName}</div>
 <div><b>Email</b> {$requestEmail}</div>
 <div><b>Phone</b> {$requestPhone}</div>
{$requestMessage}
EOT;
$textBody    = <<< EOT
From: {$requestName}
Email: {$requestEmail}
Phone: {$requestPhone}
{$requestMessage}
EOT;

// Build SendGrid payload
$payload = [
 "personalizations" => [[
   "to" => [[ "email" => $toEmail, "name" => $toName ]],
   "subject" => $subject
 ]],
 "from" => [ "email" => $fromEmail, "name" => $fromName ],
 "reply_to" => [ "email" => $replyToMail, "name" => $replyToName ],
 "content" => [
   [ "type" => "text/plain", "value" => $textBody ],
   [ "type" => "text/html",  "value" => $htmlBody ]
 ]
];

// Send via HTTPS
$ch = curl_init('https://api.sendgrid.com/v3/mail/send');
curl_setopt_array($ch, [
   CURLOPT_POST           => true,
   CURLOPT_HTTPHEADER     => [
       'Authorization: Bearer ' . $sendgridApiKey,
       'Content-Type: application/json'
   ],
   CURLOPT_POSTFIELDS     => json_encode($payload),
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_TIMEOUT        => 15
]);
error_log("Sending email ...");
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$curlErr  = curl_error($ch);
curl_close($ch);

if ($curlErr) {
   http_response_code(500);
   error_log("cURL error: " . htmlspecialchars($curlErr));
   exit;
}

// SendGrid returns 202 on success
if ($httpCode === 202) {
    echo "Your Email Has Been Sent!";
} else {
   
   http_response_code($httpCode ?: 500);
   error_log("SendGrid error (HTTP $httpCode): " . htmlspecialchars($response));
}
 The other code that I sent is on the HTML page…

 


Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


OK.

 

Nothing in that code indicates the <br> tag being sent at all.

 

You do have a couple of calls to htmlspecialchars() which would convert <br> to &lt;br &gt; and explain your problem, but you're not using it on the 'success' path (httpCode == 202)

 

Where's the code that's trying to send line breaks ?

 

 

 

 

 


ASKER CERTIFIED SOLUTION
Avatar of kenfcampkenfcamp🇺🇸

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

// SendGrid returns 202 on success
if ($httpCode === 202) {
    echo "Your Email Has Been Sent!<br>";

    echo "Thank You!<br>";
} else {

 

 

Thank you everyone!

PHP

PHP

--

Questions

--

Followers

Top Experts

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.