Using PHP in Javascript Functions

What is the best way to handle PHP blending in Javascript? Shouldn't this be done? Should this be done in a certain way? I am working on a project and I found the following javascript function:

function getStuff() {
                <?php
                $stuff = "0:Select";
                foreach ($this->stuff as $k => $v){
                    $stuff = $stuff . ";" . $v['stuff_id'] . ":" . $v['stuff_name'];
                }
                ?>

                return "<?= $stuff ?>";
            }

Assuming I need the data that PHP provides, what is the ideal way to get it? I don’t think so, but the person who wrote it is my boss, so I want to ask before I try to change it.

FYI, this JS is used in the script view, and the data for is $this->stufftransmitted from the controller that uses it.

+3
source share
3 answers

- JSON, . ( , n -deep), , javascript.

, , PHP-. /.

+3

, - Ajax (, JSON)

, "". , - , , . .

+1

There are so many ways to mix ur js with PHP. One thing you always remember:

Your PHP runs first on the server before JS is executed.

It looks like you are trying to dynamically add something to your selectbox. If so, you can do something like this

<?php
function createSelectbox( $selItems ) {
    $selTxt = "<select>";

    foreach ($selItems as $id => $value)
        $selTxt .= "<option id='" .$id. "'>". $value. "</option>";

    $selTxt .="</select>";

    return $selTxt;
}   


?>
<html>
    <head> </head>
<body>
<?php
$selItems = Array( 1 => "One", 2 => "Two", 3=> "Three" );
echo createSelectbox($selItems);
?>  
</body>
</html> 
+1
source

Source: https://habr.com/ru/post/1764816/


All Articles