php - get_the_content if it contains multiple lines it results in SyntaxError

admin2025-06-03  4

I use get_the_content to pass to a javascript variable, and then back to another PHP function. This works great, but there is an issue when using get_the_content. If the post contains only one line (no line breaks) it works great. But if the post contains line breaks I get this error in the console:

SyntaxError: '' string literal contains an unescaped line break

Using the_content doesn't work for me in this application, as it returns nothing at all.

How do I solve this?

EDIT:

This is how I pass the PHP variable to Javascript on button click:

onclick="searchEmail('<?php echo the_author_email(); ?>', '<?php echo the_title(); ?>', '<?php echo get_the_content(); ?>', '<?php echo $location ?>');"

And this is the javascript:

function searchEmail(email,title,content,location) {
  var $url = (admin_ajax.url);
  $.ajax({
    type: "POST",
    url: $url,
    datatype: "html",
    data: { 'action': 'search_notify_email', email: email, title: title, content: content, location: location },
    success: function() {
      searchNotification();
    },error:function() {
      searchNotificationError();
    }
  });
}

And lastly, this is the PHP function which receives the variable from Javascript and sends them via email:

function search_notify_email() {
  // Set variables
  $email = $_POST['email'];
  $title = $_POST['title'];
  $content = $_POST['content'];
  $location = $_POST['location'];
  // Change Email to HTML
  add_filter( 'wp_mail_content_type', 'set_email_content_type' );
    $to = $email;
    $subject = "Test subjest";
    $message = "<img src='.png'><br><b>Test!</b>";
    if (empty($title)) {
      $message .= "<br><br><b>" . $_POST['content'] . "</b> test.<br> ";
    }
    else {
      $message .= "<br><br><b>" . $_POST['content'] . "</b> test " . $_POST['title'] . " test.<br> ";
    }
    if (!empty($location)) {
      $message .= "Test <b>" . $_POST['location'] . "</b>";
    }
    $headers[] = 'From: Test <[email protected]>';

    if ( wp_mail($to, $subject, $message, $headers) ) {
      // Success
    } else {
      // Error
    }
    die();
    // Remove filter HTML content type
    remove_filter( 'wp_mail_content_type', 'set_email_content_type' );
}
add_action('wp_ajax_nopriv_search_notify_email', 'search_notify_email');
add_action('wp_ajax_search_notify_email', 'search_notify_email');

// Reset Email content type to standard text/html
function set_email_content_type() {
    return 'text/html';
}

I use get_the_content to pass to a javascript variable, and then back to another PHP function. This works great, but there is an issue when using get_the_content. If the post contains only one line (no line breaks) it works great. But if the post contains line breaks I get this error in the console:

SyntaxError: '' string literal contains an unescaped line break

Using the_content doesn't work for me in this application, as it returns nothing at all.

How do I solve this?

EDIT:

This is how I pass the PHP variable to Javascript on button click:

onclick="searchEmail('<?php echo the_author_email(); ?>', '<?php echo the_title(); ?>', '<?php echo get_the_content(); ?>', '<?php echo $location ?>');"

And this is the javascript:

function searchEmail(email,title,content,location) {
  var $url = (admin_ajax.url);
  $.ajax({
    type: "POST",
    url: $url,
    datatype: "html",
    data: { 'action': 'search_notify_email', email: email, title: title, content: content, location: location },
    success: function() {
      searchNotification();
    },error:function() {
      searchNotificationError();
    }
  });
}

And lastly, this is the PHP function which receives the variable from Javascript and sends them via email:

function search_notify_email() {
  // Set variables
  $email = $_POST['email'];
  $title = $_POST['title'];
  $content = $_POST['content'];
  $location = $_POST['location'];
  // Change Email to HTML
  add_filter( 'wp_mail_content_type', 'set_email_content_type' );
    $to = $email;
    $subject = "Test subjest";
    $message = "<img src='https://example/favicon.png'><br><b>Test!</b>";
    if (empty($title)) {
      $message .= "<br><br><b>" . $_POST['content'] . "</b> test.<br> ";
    }
    else {
      $message .= "<br><br><b>" . $_POST['content'] . "</b> test " . $_POST['title'] . " test.<br> ";
    }
    if (!empty($location)) {
      $message .= "Test <b>" . $_POST['location'] . "</b>";
    }
    $headers[] = 'From: Test <[email protected]>';

    if ( wp_mail($to, $subject, $message, $headers) ) {
      // Success
    } else {
      // Error
    }
    die();
    // Remove filter HTML content type
    remove_filter( 'wp_mail_content_type', 'set_email_content_type' );
}
add_action('wp_ajax_nopriv_search_notify_email', 'search_notify_email');
add_action('wp_ajax_search_notify_email', 'search_notify_email');

// Reset Email content type to standard text/html
function set_email_content_type() {
    return 'text/html';
}
Share Improve this question edited Feb 15, 2019 at 6:47 joq3 asked Feb 14, 2019 at 20:29 joq3joq3 3813 silver badges21 bronze badges 4
  • How are you passing to the JavaScript variable? – czerspalace Commented Feb 14, 2019 at 21:38
  • Please edit your question to show how you're passing the PHP data to JS. Also: Are you using wp_localize_script()? That's the recommended way to pass variables to JS. – Pat J Commented Feb 14, 2019 at 22:04
  • I have updated my question with the PHP variable passing to Javascript and then from javascript to the PHP function. – joq3 Commented Feb 15, 2019 at 6:48
  • 1 Instead of adding the content to the inline JS, you can pass the post id to the searchEmail function as get_the_ID(), and in the search_notify_email function use the passed post id to get the content like $content = apply_filters('the_content', get_post_field('post_content', $_POST['post_id'])); – czerspalace Commented Feb 15, 2019 at 18:08
Add a comment  | 

3 Answers 3

Reset to default 1

It sounds like you are directly echoing the php into a JavaScript variable? get_the_content makes no guarantees that the value it returns will be sanitized in the right way for a JavaScript variable.

You might try first encoding the output into JSON, and then doing that, i.e.

<script>
<?php
    ob_start();
    the_content();
    $content = ob_get_clean(); 
?>
var myVariable = <?php echo json_encode( $content ); ?>;
</script>

To be honest it may not even work. It's hacky. Dropping php into JavaScript like this is really not a recommended practice, for exactly the reason you're encountering. What this solution does is poorly imitate the proper approach for when you have PHP data (i.e. the_content) that you need in JavaScript -- AJAX.

Your JavaScript code should ask your PHP code to nicely provide sanitized data, i.e. it should make an AJAX request back to the server and your PHP code will have the opportunity to run, sanitize, and return the data cleanly.

This is the solution:

ob_start();
remove_filter ('the_content', 'wpautop'); the_content();
$content = ob_get_contents();
ob_end_clean();

Together with:

echo str_replace(array("\n", "\r"), ' + ', $content);

The only issue that remains now is that replacing the new lines with + results in duplicate + + every new line. And removing either ´\n´ or \r results in the javascript error. So how do I get around that?

The problem is JavaScript. In JavaScript you can not across a string about multiple lines without to escape the line breaks.

var longString = 'This is a very long string which needs 
                  to wrap across multiple lines because 
                  otherwise my code is unreadable.';
// SyntaxError: unterminated string literal

You could try to replace the line breaks with the + operator, a backslash, or template literals (ECMAScript 2015).

text with the + operator:

var longString = 'This is a very long string which needs ' +
                     'to wrap across multiple lines because ' +
                     'otherwise my code is unreadable.';

text with backslashs:

var longString = 'This is a very long string which needs \
    to wrap across multiple lines because \
    otherwise my code is unreadable.';

text with template literals:

var longString = `This is a very long string which needs 
                  to wrap across multiple lines because
                  otherwise my code is unreadable.`;

Source: SyntaxError: unterminated string literal - MDN web docs

Edit:

To replace the new lines you could use this code:

<?php 

// test string
$str = "This is a very long string which needs 
to wrap across multiple lines because 
otherwise my code is unreadable.";

function replace_with_plus($str)
{
    $str_array = explode ( "\n" , $str );

    $len = count( $str_array );

    $str_2 = '';
    for($i = 0; $i < $len; $i ++)
    {   
        $line = $str_array[$i];

        if($i > 0 )
        {
            $str_2 .= "'";
        }

        $str_2 .= $line;

        if($i < $len - 1  )
        {
            $str_2 .= "' + ";
        }

    }

    return $str_2;
}

?>

<script>

// replace the \n with the + operator
var test2 = '<?php echo replace_with_plus($str); ?>';

</script>

Output in the browser:

<script>

// replace the \n with the + operator
var test2 = 'This is a very long string which needs ' + 'to wrap across multiple lines because ' + 'otherwise my code is unreadable.';

</script>

Like tmdesigned said the whole think with putting the content into a JavaScript value is really buggy and not the best way.

I highly recommend you to use the way that czerspalace explained in his comment.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748897525a314636.html

最新回复(0)