简体   繁体   中英

How do I fix JS 'unterminated string literal' error

I have a form on my site that runs some basic JS validation when the user clicks submit, before the form is submitted, but I am getting an error 'unterminated string literal' when checking some of the fields.

I understand what this error is (users adding line breaks in a textarea in this case) but I cannot think of a way of avoiding/fixing it.

Here is how I declare the form -

<form id="<?php echo $form_name; ?>" 
      name="<?php echo $form_name; ?>" 
      class="standard-form" 
      method="POST" action="" 
      onsubmit="return validate_form('<?php echo $form_name; ?>')">

And here is how I am checking the field that is causing me trouble -

var your_query = document.forms['enquiry']['your_query'].value
if(your_query === ''){
    result = false;
}

Any help here would be appriciated.

Thanks.

My guess is $form_name contains a single quote character: '

First, you should really escape that output with htmlentities and json_encode :

<form id="<?php echo htmlentities($form_name); ?>"
      name="<?php echo htmlentities($form_name); ?>"
      class="standard-form"
      method="POST"
      action=""
      onsubmit="return validate_form(<?php echo htmlentities(json_encode($form_name)); ?>)">

See also Pass a PHP string to a Javascript variable (including escaping newlines)

Next, don't use that onsubmit intrinsic event attribute and don't pass the form name to it; use proper DOM scripting (or jQuery) and event handling in your JavaScript file:

(function() {
    var form = document.getElementById("<?php echo json_encode($form_name); ?>");
    form.addEventListener('submit', onSubmit, false);

    function onSubmit() {
        // manipulate variable `form` as necessary
        // without having to pass around a `form_name`
    }
}());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM