skip to Main Content

I am loading in an array from session storage that is supposed to work as a "saved" file. I use the data in the array to prefill all input elements so that the user can pick up where they left off. All input fields fill in correctly, except for dropdown elements. I make a database call using AJAX to get the options for the dropdowns. I am using the jQuery .val() to set the value of the dropdown. However, the result is null. I know everything is loading in correctly because I have checked the variables with console.log(). For some reason, I cannot set the value of the dropdown. I think it has something to do with AJAX and the database calls. I have tried putting .val() in the success and done properties of AJAX, but it still does not work. The dropdown menu fills correctly with the database call, but I cannot set the value to what I need it to be. Here is my current code:

HTML:

<select class="form-control form-control-sm"  id="channelNum" placeholder="Select Frequency" name = "channelNum">
    <option value="Select Frequency">Select Frequency</option>  
</select>

JS:

var allData = JSON.parse(sessionStorage.getItem("data"));
var freq = allData[0];
var broadcastMarket = $("input[type='radio'][name='broadcastMarket']:checked").val();
var channelNum = $('#channelNum').val();
$.ajax({
    url:"channelNum.php",
    method:"POST",
    data:{broadcastMarket : broadcastMarket, channelNum : channelNum},
    success:function(data){
        $('#channelNum').html(data);
        $('#channelNum').val(freq);
    }
}); 

PHP:

if ($result->num_rows > 0) {
  // output data from each row into dropdown menu Channel
  echo "<option value="Select Frequency">Select Frequency</option>";
  while ($row = $result->fetch_assoc()) {
    echo "<option value="$row[$freqChannels]"";
    if($channelNum == $row[$freqChannels]) {
        echo "selected='selected'";
    }
    echo ">$row[$freqChannels]</option>";
  }
}

It also does not work if I use .val() before the AJAX call. In summary, I want to set the value of "channelNum" to "freq", but it only sets it to null. Please let me know if there is any advice or solutions.

2

Answers


  1. I would first advise changing the PHP so it is more like an API, that returns JSON.

    $results = array();
    if ($result->num_rows > 0) {
      while ($row = $result->fetch_assoc()) {
        array_push($results, array(
          "label" => $row[$freqChannels],
          "value" => $row[$freqChannels]
          "selected" => $channelNum == $row[$freqChannels]
        ));
      }
    }
    // Close SQL Connection
    // Send JSON to Browser
    header('Content-type: application/json');
    echo json_encode($results);
    

    This way you can call the PHP via AJAX and get a quick result. You can then transform that into HTML.

    var allData = JSON.parse(sessionStorage.getItem("data"));
    var freq = allData[0];
    var broadcastMarket = $("input[type='radio'][name='broadcastMarket']:checked").val();
    var channelNum = $('#channelNum').val();
    $.ajax({
      url:"channelNum.php",
      method:"POST",
      data:{
        broadcastMarket: broadcastMarket,
        channelNum: channelNum
      },
      success:function(data){
        $('#channelNum').empty();
        $.each(data, function(i, v){
          $('#channelNum').append($("<option>", {
            value: v.value
          }).prop("selected", v.selected).html(v.label));
        });
      }
    });
    

    So for example, when you call the PHP you will get JSON results:

    [
      {
        "label": "My first Pick",
        "value": "first".
        "selected": false
      },
      {
        "label": "Second Choice",
        "value": "second",
        "Selected": true 
      }
    ]
    

    This then becomes HTML.

    <option values="first" selected="false">My first Pick</option>
    <option values="second" selected="true">Second choice</option>
    
    Login or Signup to reply.
  2. Without an actual sample of your PHP response and knowing what was stored in your local storage we can only guess. The following snippet demonstrates that your original snippet should actually work, provided the data you receive from your PHP function looks something like below and that the first element in your parsed allData JSON string is actually one of the possible values in your select element:

    // Set up some test data:
    const data=`<option>please select ...</option><option selected>one</option><option>two</option><option>three</option><option>four</option>`;
    
    var allData = JSON.parse(`["three",1,2,3]`);
    // assuming, that allData really _is_ an array ...
    var freq = allData[0];
    
    // Knowing that your options were well filled 
    // I assume that the AJAX call went well,
    // so I can leave it out here ...
    // ... somewhere in the success callback:
        $('#channelNum').html(data);
        $('#channelNum').val(freq);
    <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
    <select class="form-control form-control-sm"  id="channelNum" placeholder="Select Frequency" name = "channelNum">
    <option value="Select Frequency">Select Frequency</option>  
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search