skip to Main Content

I have a select dropdown that I want to update with dynamic data every few seconds without refreshing the page. The data should be retrieved from a PHP script using PDO and returned as a JSON response.

The problem is that the retrieved data is not displaying on the select dropdown, it is displaying on the body as an array and sometimes turns the whole page into raw HTML. what am I doing wrong?

Here’s what I’ve tried so far:

<?php
// PHP script to create an array of numbers from 1-10
$numbers = range(1, 10);
header('Content-Type: application/json');

echo json_encode($numbers);
?>

And here’s the JavaScript code that I’m using to update the select dropdown:

</script> 
function updateNumbers() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'get_numbers.php');
  xhr.onload = function() {
    if (xhr.status === 200) {
      var numbers = JSON.parse(xhr.responseText);
      var select = document.getElementById('numbers-select');
      select.innerHTML = '';
      for (var i = 0; i < numbers.length; i++) {
        var option = document.createElement('option');
        option.text = numbers[i];
        select.add(option);
      }
    }
  };
  xhr.send();
}

// call function to populate select dropdown on page load
updateNumbers();

// set interval to update select dropdown every 5 seconds
setInterval(updateNumbers, 5000); </script>
//HTML CODE FOR SELECT DROPDOWN    
<select id="numbers-select"></select>

When I run this code, the select dropdown is empty and the data is displayed on the body of the page as an array ([1,2,3,4,5,6,7,8,9,10]). What am I doing wrong? Can someone please help me with this?

Thanks in advance!

2

Answers


  1. Your JavaScript has syntax errors (just some stray s in 3 places) – you should have a console error about that, which would stop it from working. And add is not a valid DOM function you can run on an element. To attach and element as a child of another one (such as an option into a select) you need appendChild.

    It’s unclear why/how the data would just show up on the page instead…unless get_numbers.php is also the same PHP script in which you have got your JavaScript and HTML. You should keep the script which generates the numbers separate, so all it does is respond to the AJAX and return pure JSON.

    Working demo of the client-side code (using a static data source instead of the PHP):

    function updateNumbers() {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', 'https://api.jsonbin.io/v3/b/643c69dac0e7653a05a5a41f?meta=false');
      xhr.onload = function() {
        if (xhr.status === 200) {
          var numbers = JSON.parse(xhr.responseText);
          var select = document.getElementById('numbers-select');
          select.innerHTML = '';
          for (var i = 0; i < numbers.length; i++) {
            var option = document.createElement('option');
            option.text = numbers[i];
            select.add(option);
          }
        }
      };
      xhr.send();
    }
    
    // call function to populate select dropdown on page load
    updateNumbers();
    
    // set interval to update select dropdown every 5 seconds
    setInterval(updateNumbers, 5000);
    <select id="numbers-select"></select>
    Login or Signup to reply.
  2. Based on your code, it looks like there is a misplaced closing tag before the "HTML CODE FOR SELECT DROPDOWN" comment, which may cause the issue you are experiencing. Additionally, the script should be wrapped within the tags.

    Here’s the corrected code:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Dynamic Select Dropdown</title>
    </head>
    <body>
        <select id="numbers-select"></select>
        
        <script>
        function updateNumbers() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'get_numbers.php');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    var numbers = JSON.parse(xhr.responseText);
                    var select = document.getElementById('numbers-select');
                    select.innerHTML = '';
                    for (var i = 0; i < numbers.length; i++) {
                        var option = document.createElement('option');
                        option.text = numbers[i];
                        select.add(option);
                    }
                }
            };
            xhr.send();
        }
    
        // call function to populate select dropdown on page load
        updateNumbers();
    
        // set interval to update select dropdown every 5 seconds
        setInterval(updateNumbers, 5000);
        </script>
    </body>
    </html>
    

    I’ve wrapped your JavaScript code within a tag, and I’ve removed the misplaced closing tag.

    Make sure your get_numbers.php script is in the same directory as your HTML file, and its content is as follows:

    <?php
    // PHP script to create an array of numbers from 1-10
    $numbers = range(1, 10);
    header('Content-Type: application/json');
    
    echo json_encode($numbers);
    ?>
    

    This should resolve the issue with the select dropdown not being populated correctly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search