Jump to content

Choices.js cannot "re"setValue() via ajax

Go to solution Solved by requinix,

Recommended Posts

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 data
choices.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,

Ajax Code

let shiftDate = document.getElementById('reservation_shift_date');
      shiftDate.addEventListener("change", function(){
          let request = new XMLHttpRequest();
          request.onreadystatechange = function(){
              if(request.readyState == 4 && request.status == 200){



if($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['date'])){

  $stmt = $conn->prepare("SELECT table_id FROM reservation WHERE shift_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);


Link to comment
Share on other sites

  • Solution

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...

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.