amirelgohary1990 Posted June 1 Share Posted June 1 I am retrieving data via Ajax into Choices.js select options My scenario is when I select date, getting the available restaurant tables The retrieving data is 100% working, but it reflects in the select options only in the first request, then when I try to reselect another date I receive the below console error, and choices still keep the initial retrieved datachoices.min.js:11 Trying to initialise Choices on element already initialised Choices setValue Function var el = document.getElementsByClassName("table_number")[0]; if (el) { function setChoices(values) { const tableNumbers = new Choices(el, { removeItemButton: true, }).setValue(values); } setChoices(values); } Ajax Code let shiftDate = document.getElementById('reservation_shift_date'); shiftDate.addEventListener("change", function(){ let request = new XMLHttpRequest(); request.open("POST","get_tables.php",true); request.setRequestHeader("content-type","application/x-www-form-urlencoded"); request.onreadystatechange = function(){ if(request.readyState == 4 && request.status == 200){ setChoices(JSON.parse(request.responseText)); } } request.send("date="+shiftDate.value); }); get_tables.php if($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['date'])){ $stmt = $conn->prepare("SELECT table_id FROM reservation WHERE shift_date = ?"); $stmt->execute([$_POST['date']]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach($rows as $row){ $reserved_tables_id[] = $row['table_id']; } $in = implode(',',$reserved_tables_id); $execute_query = mysqli_query($dbConnection,"SELECT id, table_name FROM tables WHERE id NOT IN ($in)"); while($row = mysqli_fetch_assoc($execute_query)){ $tbl_id = $row['id']; $tbl_name = $row['table_name']; $arr[] = ["value"=>$tbl_id,"label"=>$tbl_name]; } echo json_encode($arr); } Quote Link to comment Share on other sites More sharing options...
Solution requinix Posted June 2 Solution Share Posted June 2 Your setChoices creates a new Choices object every time. Evidently the API doesn't like that. You need to create your Choices just once, such as in its own variable (defined outside the function). Feel like you've got some slightly larger issues with design here, though... Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.