Question

This Ajax is not retrieving any information from its' PHP file as it should, and when inspecting the Javascript in Firebug I noticed that responseText is returning undefined.

Here is the Javascript:

function getTeams(sport)
{
    var req = new XMLHttpRequest();
    var nextTeam, nextOption;

    // callback function, using "closure"
    req.onreadystatechange = function()
    {
        if( (req.readyState == 4) && (req.status == 200) )
        {
            var result = req.responseText;

            // array teams created here
            var teams = result.split(", ");

            for(var i = 0; i < teams.length; i++)
            {
                nextTeam = teams[i];
                nextOption = new Option(nextTeam);

                /* add the new option to the option list
                 ("null" for IE5, "-1" for all other browsers) */
                try
                {
                    document.getElementById("teamsList").add(nextOption, -1);
                }
                catch(e)
                {
                    document.getElementById("teamsList").add(nextOption, null);
                }
            }
        }
    } // end of closure

    req.open("GET", "favoriteSport.php?sport=" + sport, true);
    req.send(null);
}<br /><br />

Here is the PHP:

<?php
    $sport = $_GET["sport"];

    $teams = array("basketball" => "Atlanta Hawks, Chicago Bulls, New York Knicks",
                    "baseball" => "Atlanta Braves, Chicago Cubs, New York Yankees",
                    "football" => "Atlanta Falcons, Chicago Bears, New York Giants");

    return $teams[$sport];
?><br /><br />

...and here is the relevant html:

    <select onchange = "getTeams(this.value);">
        <option>
            --select a sport--
        </option>
        <option value = "basketball">
            basketball
        </option>
        <option value = "baseball">
            baseball
        </option>
        <option value = "football">
            football
        </option>
    </select>

    <select id = "teamsList"></select>
Was it helpful?

Solution

It looks like your issue is here:

return $teams[$sport];

Try

echo $teams[$sport];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top