X3minater
X3minater

Reputation: 99

PHP code in innerHTML

I'm trying to have my code add this 2 fields to a form (quantities and products) on a click of a button.

How do I format my script so the innerHTML can include php code? Or is there another way to add a select element via JS?

newdiv.innerHTML = "<input type='text' name='quantities[]'> <select name='products[]'>
                        <?php
                            $sql = mysqli_query($link, "SELECT name FROM inventory");
                            while ($row = $sql->fetch_assoc()){
                                echo "<option value=\"".$row['name']."\">" . $row['name'] . "</option>";
                            }
                        ?>
                    </select>";

Upvotes: 0

Views: 151

Answers (1)

stephenlcurtis
stephenlcurtis

Reputation: 190

PHP code is interpreted by your server before the page is even sent to the browser. The server then sends a completed html page (no PHP code) across the internet to your browser, which then loads it and then executes the JavaScript in the browser. The PHP interpreter would have no way of reading what the JavaScript changes on the finished page.

You might want to look into making an Ajax call to a PHP page, your PHP page can then contain the sql query and return data the JavaScript can use to add the options.

Upvotes: 3

Related Questions