How to get SQL Table element id from search select made using jquery?

37 views Asked by At

I have made the search bar that searches for a project bucket and shows auto complete suggestions below. When required project bucket is selected there is a add task button that takes to add task form to create task with foreign key as selected bucket id (TM_BUCKET_ID key for TM_TASK_BUCKET_ID).

This is my search bar logic in jquery where i have tried to put the bucket id in the url and req from url in my task controller but it can not get the id from url

$(document).ready(function () {
    const bucketSearchInput = $('#bucketSearch');
    const autocompleteResults = $('#autocomplete-results');
    const bucketInfoContainer = $('#bucketInfo');
  
    const fetchAutocompleteSuggestions = async (query) => {
      try {
        const response = await fetch(`/task/searchBar?q=${query}`);
        const suggestions = await response.json();
        return suggestions;
      } catch (error) {
        console.error('Error fetching autocomplete suggestions:', error);
      }
    };
  
    const updateAutocompleteResults = async () => {
      const query = bucketSearchInput.val();
      if (query.length === 0) {
        autocompleteResults.empty();
        return;
      }
  
      const suggestions = await fetchAutocompleteSuggestions(query);
  
      autocompleteResults.empty();
      suggestions.forEach((suggestion) => {
        const listItem = $('<div class="autocomplete-item"></div>').text(suggestion.TM_BUCKET_NAME);
        listItem.on('click', () => handleAutocompleteSelection(suggestion));
        autocompleteResults.append(listItem);
      });
    };
  
    const handleAutocompleteSelection = (selectedBucket) => {
      const selectedBucketId = selectedBucket.TM_BUCKET_ID;
      bucketInfoContainer.empty();
      bucketInfoContainer.text( selectedBucket.TM_BUCKET_NAME);
      window.location.href = '/task/addTask?bucketId=' + selectedBucketId;
    };

    bucketSearchInput.on('input', updateAutocompleteResults);
  
    $(document).on('click', (event) => {
      if (!$(event.target).closest('#autocomplete-results').length) {
        autocompleteResults.empty();
      }
    });
  });

My add task controller

async function handleAddTask(req, res) {

// here i have tried to get the bucket id from url

    const bucketId = req.params.bucketId;
      const { title, details } = req.body;
  try{
    const newTask = await taskModel.create({
    TM_TASK_BUCKET_ID: bucketId ,
    TM_TASK_NAME: title,
    TM_TASK_DESCRIPTION: details,
    TM_TASK_CREATED_BY: req.user.userId,
    TM_TASK_CREATED_ON: new Date(),
  })
  res.redirect('../views/bucket/task', { newTask });
  }catch(error){
    console.log('Error creating task:', error);
    res.redirect('/task')
  }
  }

I have tried following ways to resolve it

  1. put the bucket id in the url and tried to get it with req.params in task controllers as above code.

  2. send the bucket id in add task form as hidden input field.

    With following jquery in search bar logic

const handleAutocompleteSelection = (selectedBucket) => {
    const selectedBucketId = selectedBucket.TM_BUCKET_ID;
    $('#bucketId').val(selectedBucketId);
};

And add task form with

<form action="/task/addTask" method="post">
    <input type="hidden" name="bucketId" id="bucketId" value="">
    <!-- other entries  -->
    <button type="submit">Create Task</button>
</form>

and in task controllers

async function handleAddTask(req, res) {

    const bucketId = req.body.bucketId;
      const { title, details } = req.body;
  try{
    const newTask = await taskModel.create({
    TM_TASK_BUCKET_ID: bucketId ,
    TM_TASK_NAME: title,
    TM_TASK_DESCRIPTION: details,
    TM_TASK_CREATED_BY: req.user.userId,
    TM_TASK_CREATED_ON: new Date(),
  })
  res.redirect('../views/bucket/task', { newTask });
  }catch(error){
    console.log('Error creating task:', error);
    res.redirect('/task')
  }
  }

I believe there might be some error in my code or I might be missing out on something. Please Help.

0

There are 0 answers