John John - 5 months ago 14
Javascript Question

Set initial value of dropdown output constructed with ajax

I have the following dropdown list which changes the output of

<div id="item"></div>
with ajax when select option is changed. I'm not using select2.

<?php
$biqsQuery = "SELECT biq.biqid, biq.name FROM biq";
$biqs = $db->query($biqsQuery);
?>

<select name="itemselector" id="itemselect">
<?php foreach ($biqs ->fetchAll() as $biq): ?>
<option value="<?php echo $biq['biqid']);?>">
<?php echo e($biq['name']);?>
</option>
<?php endforeach; ?>
</select>

<div id="item"></div>


PHP File:



if(isset($_GET['itemselector'])){



$biqQuery = "SELECT biq.biqid, biq.name, biq.img
FROM biq
WHERE biq.biqid= :biqid ";

$biq= $db ->prepare($biqQuery);

$biq->execute(['biqid' => $_GET['itemselector']]);

$selectedBiq=$biq->fetch(PDO::FETCH_ASSOC);

echo '<img src="'. $selectedBiq['img']. '">';
}


Javascript File:



$('#itemselect').on('change',function(){
var self = $(this);

$.ajax({
url: '../helpers/biq.php',
type: 'GET',
data: {itemselector : self.val()},
success: function(data){

$('#item').html(data);
}
});
});


It's currently succesfully changing the output, no problem on that part.

But when the page is first loaded, it shows the first value of the table on the dropdown menu, however it doesnt output the image of that first value into
<div>
.

What i need is; when the page is loaded i need the first entry in the database to be outputted into the
<div id="item"></div>
automatically.


Any help is appreciated, thanks in advance.

Answer

you could write on body load event to accomplish this. please correct if any type mistake will there but this will help you to get it rid

$(document).ready(function(){
  var first = $("#itemselect option:first").val();
  $.ajax({
    url: '../helpers/biq.php',
    type: 'GET',
    data: {itemselector : first},
     success: function(data){
         $('#item').html(data);
     }
  });
}); 

Comments