I am beginner at AJAX. There are two Select Menus: Month & Year. The objective is to display data in the table AFTER selection of YEAR. Based upon selected values data should be displayed in the table.

Thanks a lot in advanced.

<!DOCTYPE html>
<?php
    $year=$_GET["year"];
    $month=$_GET["month"];

    $year = array(
        "2009"=>"2009",
        "2010"=>"2010",
        "2011"=>"2011",
        "2012"=>"2012",
        "2013"=>"2013",
        "2014"=>"2014",
        "2015"=>"2015"
    );

    $month = array(
        "Jan"=>"Jan",
        "Feb"=>"Feb",
        "March"=>"March",
        "April"=>"April",
        "May"=>"May",
        "June"=>"June",
        "July"=>"July",
        "August"=>"August",
        "Sept"=>"Sept",
        "Oct"=>"Oct",
        "Nov"=>"Nov",
        "Dec"=>"Dec"
    );

    $query = "select * from dashboard WHERE month(creation) = '".$month."' AND year(creation) = '".$year."' ";
    $result = mysql_query($query);

    while(mysql_fetch_array($result))
    { 
        echo "<tr>";
            echo "<td>" . $row['creation'] . "</td>";
            echo "<td>" . $row['username'] . "</td>";
            echo "<td>" . $row['lastname'] . "</td>";
        echo "</tr>";
    }                           
?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />        
        <script>
            function showDashboard(year)
            {
                if (year=="")
                  {
                  document.getElementById("monthYear").innerHTML="";
                  return;
                  } 
                if (window.XMLHttpRequest)
                  {// code for IE7+, Firefox, Chrome, Opera, Safari
                  xmlhttp=new XMLHttpRequest();
                  }
                else
                  {// code for IE6, IE5
                  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                  }
                xmlhttp.onreadystatechange=function()
                  {
                  if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                    document.getElementById("monthYear").innerHTML=xmlhttp.responseText;
                    }
              }
            xmlhttp.open("GET","dashboard.php"+year,true);
            xmlhttp.send();
            }
            </script>
    </head>
<body>

                    <form name="dashboard" action="dashboard.php" method="POST" >
                        <div style="padding-top:30px; padding-left:20px; margin:15px;">
                            Month:&nbsp;&nbsp;
                            <select name="month" id="byMonth" onchange="showDashboard(this.value)" >
                              <option value="key" selected="selected"> Select Month </option>
                              <?php
                                foreach($month as $key => $value){
                                   echo '<option value="'.$key.'">'.$value.'</option>';
                               }
                              ?>
                            </select>
                            Year:
                            <select name="year" id="byYear" onchange="showDashboard(this.value)">
                              <option value="key" selected="selected"> Select Year </option>
                              <?php
                                foreach($year as $key => $value){
                                   echo '<option value="'.$key.'">'.$value.'</option>';
                               }
                              ?>
                            </select>

                        </div>
                    </form>
                    <div id="monthYear">Dashboard info will be listed here.</div>
                    <div class="TableDashboard" >
                        <table >
                            <tr>
                                <td>Date</td>
                                <td>username</td>
                                <td>lastname</td>
                            </tr>
                        </table>
                    </div>
    </body>
</html>  

Dani AI

Generated

Two root causes appear in this thread: the client code was not sending parameters reliably, and the server code used $_GET values without checking for them first (hence the "Undefined index" warnings that spotted). Splitting the logic into two files, as eventually did, is a valid quick fix — but a single, robust endpoint that validates inputs and returns structured data (JSON) is cleaner and easier to debug.

Practical checklist and a minimal pattern that works reliably:

  • Make the year select drive the action (listen for its change) and read the month value at that moment.
  • Build the request with proper query parameters (or POST body), not by naive string concatenation.
  • On the server, use input filtering (or isset) to avoid undefined-index warnings and use prepared statements (PDO or mysqli) to prevent SQL injection.
  • Return JSON and let client code render table rows; this separates data from presentation and simplifies debugging.

Example client fetch flow (keeps the network call explicit and safe):

const params = new URLSearchParams({ month: monthVal, year: yearVal });
fetch('ajax.php?' + params.toString())
  .then(res => { if (!res.ok) throw new Error(res.statusText); return res.json(); })
  .then(rows => {
    document.getElementById('tableBody').innerHTML =
      rows.map(r => `<tr><td>${r.creation}</td><td>${r.username}</td><td>${r.lastname}</td></tr>`).join('');
  })
  .catch(err => console.error('AJAX error:', err));

Server-side summary: call filter_input() or check isset($_GET['year']), validate/convert the month to a number if needed, run a prepared query with PDO/mysqli, set the JSON content-type header, and echo json_encode($results). Troubleshooting tips: use the browser Network tab to confirm the request URL and server response, console.log selected values before the fetch, ensure the default select option has an empty value (not "key"), and prevent the form from submitting when using AJAX.

Recommended Answers

All 4 Replies

Member Avatar for Member #949455

I am beginner at AJAX. There are two Select Menus: Month & Year. The objective is to display data in the table AFTER selection of YEAR.

I don't consider you as a beginner.

What error you have so far when you ran the code?

Is this the issue you are having from the other thread?

What error you have so far when you ran the code?

There is an issue for line 3 & 4.

Undefined index: month<br />
Undefined index: year<br />

Action should be performed AFTER selecting year value. It is not giving result as per selected item.

In short i need to get the selected values in ajax and show data based on selected values in table.

Thanks a lot in adv.

Finally, i solved it out. I made two files to get the data from database. It seems for AJAX, one may use two files instead of doing all stuff in single file.

//dashboard.php

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            function showDashboard(year)
            {
                try
                {
                    month = $('#byMonth :selected').val();  
                    year = $('#byYear :selected').val(); 

                    if (year=="")
                    {
                        document.getElementById("monthYear").innerHTML="";
                        return;
                    } 
                    if (window.XMLHttpRequest)
                    {// code for IE7+, Firefox, Chrome, Opera, Safari
                        xmlhttp=new XMLHttpRequest();
                    }
                    else
                    {// code for IE6, IE5
                        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                    }

                    xmlhttp.onreadystatechange=function()
                    {
                        if (xmlhttp.readyState==4 && xmlhttp.status==200)
                        {
                            alert(xmlhttp.responseText);
                            document.getElementById("tableContentID").innerHTML=xmlhttp.responseText;
                        }
                    }
                    xmlhttp.open("GET",URL,true); 
                    xmlhttp.send();
                }
                catch(err){
                alert(err.message);
                }
            }
            </script>

// ajax.php

    $SelectedMonth = $_GET['month'];   
    $SelectedYear = $_GET['year']; 
    $query = "";
    $result = mysql_query($query);  
    while($row=mysql_fetch_array($result))
    {       
        echo "<tbody>";
            echo "<tr>";
                echo "<td>" . $row['creation'] . "</td>";
                echo "<td>" . $row['username'] . "</td>";
                echo "<td>" . $row['lastname'] . "</td>";
            echo "</tr>";
        echo "</tbody>";
    }                           
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.