skip to Main Content

Not quite sure what I’m doing wrong. I have

$description = addslashes($description);
echo "<option onclick='updateTotals(`$urlOptions`,`$option_title`,`$description`)' value='".$description."' selected> ".$description."</option>";

An example of the text I’m trying to escape is

422458 - 120' Boom if NOZZLE BODIES is CR II single nozzle body

The source code shows the slashes added in, but the code isn’t acknowledging the slash?

enter image description here

2

Answers


  1. If your purpose is to produce strings in a fragment of JavaScript code then you better use json_encode(). It escapes all characters that need to be escaped in JavaScript and also puts quotes around it producing a valid JavaScript string literal.

    A short fragment of PHP code is better than any explanation:

    // a list of characters, including quotes
    $value = implode('', ['a', "'", 'b', '"', 'c', "n", 'd', "\", 'e']);
    
    echo("const value = " . json_encode($value) . ";n");
    

    Its output is:

    const value = "a'b"cnd\e";
    

    Check it online.

    In fact, json_encode() is the best way to encode any data structure if your goal is to generate a fragment of JavaScript code.

    Login or Signup to reply.
  2. $description can broke your option in several ways. I’s better to define a function to be called onclick, but going further, it’s better to trigger the function onchange the select.

    Take a look to this example:

    <?php
    
    $description3 = '<p>This is a single quote: '</p>'; //Escape ' with 
    
    $myOptions = array(
        'val1' => array(
            'text' => 'Option 1',
            'url' => 'https://url1.com',
            'title' => 'This is Option 1',
            'description' => '<p>This is description for <b>Option 1</b>.</p>',
        ),
        'val2' => array(
            'text' => 'Option 2',
            'url' => 'https://url2.com',
            'title' => 'This is Option 2',
            'description' => '<p>This is description for <b>Option 2</b>.</p>',
        ),
        'val3' => array(
            'text' => 'Option 3',
            'url' => 'https://url3.com',
            'title' => 'This is Option 3',
            'description' => $description3, //No need to escape anything
        ),
    );
    
    ?>
    <script>
    var myOptions = <?php echo json_encode($myOptions); ?>;
    
    function mySelectChanged(value)
    {
        //Call your original function
        updateTotals(myOptions[value].url, myOptions[value].title, myOptions[value].description);
    }
    </script>
    
    <select id="mySelect" onchange="mySelectChanged(this.value);">
    <?php
    foreach ($myOptions as $value=>$option) {
        printf('<option value="%s">%s</option>', $value, $option['text']);
    }
    </select>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search