无法将php变量作为参数传递给javascript函数[关闭]

The case is that I have a .php file and inside it, I have a function inside script tags. After it, I have php code, that reads from a file. I want to sent the file data to the js function. I had done this before, but now it will produce parsing errors.

SOLUTION

THE file format must not have line breaks!!!!
echo '<script>updateMatch1("'.$filetext.'") </script>';

Here is the code

<script>
    function updateMatch1(names) {
    alert(names);
};
</script>
<?php
    /* Read file */
    ...
    $filetext = fread( $file, $filesize ); //checked the output, it's ok

    // numerous ways I tried. Some produce an error and the page isn't loaded at all,
        // while others produce an error in the console
    echo "<script>updateMatch1('" . $filetext . "');</script>";
    //echo '<script> updateMatch1($filetext);</script>';
    //echo '<script>updateMatch1();</script>';
    //echo "<script>updateMatch1($filetext" . ")</script>";
    //echo "<script>updateMatch1($filetext)</script>";
        //echo '<script>updateMatch1(' . $filetext  . ');</script>';
?>

Check your file.txt. Maybe it contains some illegal character or has some incompatible file encoding that produce the illegal character. If you print the value of $filetext with php, there is no visible error, but it can produce some in JS. E.g. it can be the zero-width space. See if you have spaces or other characters on the end of the file.

If you did not hide anything from your code, then this dots are producing parse error

/* Read file */
    ...

You should get rid of ...

Also, have in mind that:

<?php $filetext = "alalala"; ?>
<script>
    updateMatch1('<?=$filetext;?>');
</script>

Will produce the correct alert 'alalala', but:

<?php $filetext = "alal'ala"; ?>
<script>
    updateMatch1('<?=$filetext;?>');
</script>

will produce:

SyntaxError: missing ) after argument list


updateMatch1('alal'ala');

Escape your file output before pass to js.

You can try a simple escape:

<?php $filetext = "alal'ala"; ?>
<script>
    updateMatch1('<?= htmlspecialchars($filetext, ENT_QUOTES);?>');
</script>

There are lots of dupicate questions on stackoverflow dont ask everything just search bro!!!

For samples:

  1. how to pass php parameter to javascript
  2. How to pass JavaScript variables to PHP?
  3. Passing parameters to Javascript using PHP

Answer was given by @iMx!!

The reason was that the .txt file contained line breaks. These would break the syntax. The solution was to separate the names by whitespaces, instead of newlines, and everything was ok!

echo '<script>updateMatch1("'.$filetext.'") </script>';