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
I would first advise changing the PHP so it is more like an API, that returns JSON.
This way you can call the PHP via AJAX and get a quick result. You can then transform that into HTML.
So for example, when you call the PHP you will get JSON results:
This then becomes HTML.
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 parsedallData
JSON string is actually one of the possible values in yourselect
element: