简体   繁体   中英

Outputting XML Information using PHP and AJAX based on Select Option

I am attempting to pull data from XML using PHP and AJAX based on the option selected from a Select box.

I do not get any output on selection change.

HTML

<?php
    session_start();

    // Change the connection info in this file
    require 'dbInfo.php';
?>
<!DOCTYPE html>
<html>
<head>
    <title>Member Page</title>
    <script type="text/javascript">
        // AJAX to show info for the selected City
        function ShowCityInfo(citySelection) 
        {
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function(){
                if (this.readyState == 4 && this.status == 200){
                    document.getElementById('cityInfo').innerHTML = this.responseText;
                }
            };
            xmlhttp.open("GET", "getCityData.php?city=" + citySelection, true);
            xmlhttp.send();
        }

        // AJAX to show info for the selected Rider
        function ShowRiderInfo(rider) 
        {
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function(){
                if (this.readyState == 4 && this.status == 200){
                    document.getElementById('riderInfo').innerHTML = this.responseText;
                }
            };
            xmlhttp.open("GET", "getRiderInfo.php?rider=" + rider, true);
            xmlhttp.send();
        }
    </script>
</head>
<body>
    <h1>Welcome User!</h1>
    <?php
        // If there is not a valid user logged in, kick back to login page
        if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
            header("Location:login.php");
            exit();
        }
        else { // Welcome the valid user
            echo "<h1>" . $_SESSION['user'] . "'s Member Page </h1>";
        }

        // Clear the session if the user is logged out based on query string
        if (isset($_GET['loggedOut'])) {
            session_unset();
            session_destroy();

            // Redirect to login and exit the script execution
            header("Location:login.php");
            exit();
        }

    ?><br/>

    <!-- On submission use query string to set that the user is logged out.
         Would be reverted by isset above on reload -->
    <form action="member.php?loggedOut=true" method="POST">
        <input type="submit" name="logOut" value="Log Out"><br/>
    </form>


    <?php
        $conn = new mysqli($host, $username, $password, $db);

        // Check for connection error
        if ($conn->connect_error) {
            die("Connection error: " . $conn->connect_error);
        }  
    ?>

    <br/><br/>

    <strong>Select a City for more Information</strong> <br/>
    <!-- Populate selection from DB -->
    <select name="cities" onchange="ShowCityInfo(this.value)">
        <option>Select a City</option>
        <?php
            $sql = "SELECT * FROM webData.nwoCity";

            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    // Populate the select options from DB city names and set value to the ID
                    echo '<option value=" '. $row["cityID"] . '">'. $row["name"] . '</option>'; 
                }
            }

            $conn->close();
        ?>
    </select>

    <!-- Will be populated by AJAX -->
    <div id="cityInfo"></div>

    <h2>Artistic Freedom</h2>
    <p>This populates from XML using AJAX</p>

    <select name="riders" onchange="ShowRiderInfo(this.value)">
        <option><strong>Select a Rider:</strong></option>
        <option value="Ryan Dungey">Ryan Dungey</option>
        <option value="Ken Roczen">Ken Roczen</option>
        <option value="Eli Tomac">Eli Tomac</option>
        <option value="Dean Wilson">Dean Wilson</option>
    </select>

    <br/><br/>
    <div id="riderInfo"></div>

</body>
</html>

PHP

<?php
    $riderSelection = $_GET["rider"];

    // Create a DOM Document and load the XML file
    $xmlDoc = new DOMDocument();
    $xmlDoc->load("riderLineup.xml");

    // Get the rider elements
    $x = $xmlDoc->getElementsByTagName('RIDER');

    // Find all the rider elements that match the name
    for ($i = 0; $i < $x->length ; $i++) 
    { 
        // Only process the nodes in each element
        if ($x->item($i)->nodeType == 1) 
        {
            if ($x->item($i)->childNodes->item(0)->nodeValue == $riderSelection) 
            {
                $y = ($x->item($i)->parentNode);
            }
        }
    }

    $rider = ($y->childNodes);

    // Output the rider information to be used by AJAX as a response
    for ($i = 0; $i < $rider->length; $i++) 
    { 
        // Only process nodes in elements
        if ($rider->item($i)->nodeType == 1) 
        {
            // Element node name in bold
            echo "<strong>" . $rider->item($i)->nodeName . "</strong>";

            // Element node's value
            echo $rider->item($i)->childNodes->item(0)->nodeValue;

            echo "<br/>";
        }
    }

?>

XML

<LINEUP>
    <RIDER>
        <NAME>Ryan Dungey</NAME>
        <AGE>27</AGE>
        <NICKNAME>The Diesel</NICKNAME>
        <NUMBER>1</NUMBER>
        <BRAND>KTM</BRAND>
        <CHAMPIONSHIPS>7</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Ken Roczen</NAME>
        <AGE>22</AGE>
        <NICKNAME>Kenny</NICKNAME>
        <NUMBER>94</NUMBER>
        <BRAND>Honda</BRAND>
        <CHAMPIONSHIPS>3</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Eli Tomac</NAME>
        <AGE>25</AGE>
        <NICKNAME>ET3</NICKNAME>
        <NUMBER>3</NUMBER>
        <BRAND>Kawasaki</BRAND>
        <CHAMPIONSHIPS>1</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Dean Wilson</NAME>
        <AGE>26</AGE>
        <NICKNAME>Deano</NICKNAME>
        <NUMBER>15</NUMBER>
        <BRAND>Husqvarna</BRAND>
        <CHAMPIONSHIPS>1</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Benny Bloss</NAME>
        <AGE>20</AGE>
        <NICKNAME>The Baby Giraffe</NICKNAME>
        <NUMBER>34</NUMBER>
        <BRAND>KTM</BRAND>
        <CHAMPIONSHIPS>0</CHAMPIONSHIPS>
    </RIDER>
</LINEUP>

When I run the main page I see the Rider selection box but changing the selection does not result in any output.

Yes this code did start as code for an assignment for a College course. However, this assignment has already been submitted to the professor for marking and I am just trying to go back and understand the concepts better. This code regarding getting the info from XML was not a component of the assigned work.

In the PHP file where I had coded:

 $x = $xmlDoc->getElementsByTagName('RIDER');

Should have read:

$x = $xmlDoc->getElementsByTagName('NAME');

I was grabbing the <RIDER> elements instead of all the <NAME> nodes of the <RIDER> elements. Changing said line fixed the issue.

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