简体   繁体   中英

Defining a JS function in PHP

I am Working on a little Webpage, which has a .php-include hierarchy. Now I want to generate two relying Dropdown-Menues, where the second one is updated, after you choose an option in the first one.

I would prefer if the code for this page could stay in one file, as I want to achieve this without splitting the code.

The code looks something like this:

<?php
echo '<div id="dashheader">
<form action="..." method="get" enctype="text/plain">
<p id="dashheadline">Selbstkosten ermitteln</p>
..
<td><select name="lieferant" onChange="javascript:updateArtikel(this.value);" >
...
<div id="art">
    <select name="artikel">
    <option value="">Erst Lieferanten wählen</option>
    </select>
</div>';
?>

Now i have the Javascript which I want to be executed on a Change in the "lieferant"-Dropdown(Simple Ajax Call):

<script type="text/javascript">
    function updateArtikel(str) {
        ...
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("art").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","cure1.php?q="+str,true);
        xmlhttp.send();
        ...
     }
</script>

cure1.php is the same .php-File I generate the Output in. It also contains additional php-Code, in Case it is called with a parameter "q" (see AJAX-Call):

if(isset($_GET['q'])){
    echo '<select id="art" name="artikel">';
    $abfrage = //MYSQL-Query; 
    $ergebnis = mysqli_query($con,$abfrage);
    while($row = mysqli_fetch_object($ergebnis))
    {
        echo '<option value = "'.$row->PositionsNr.'" > '.$row->Artikelbezeichnung.'</option>';
    }
    echo '</select>';
}

Now the Question: Is it really possible to leave this code in one File? If not, How shall I put the code, if the "cure1.php" (my page) is loaded per "index.php?menu=10" ?

see your hierarchy of php file carefully. At last code should like

<?php 
......
//php code
?>
<html>
    <head>
        <script>
          //javascript code
        </script>
    </head>
</html>

you may also echo all html code within php tags. This is standard, you may not restricted to do same.

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