Why is my Jquery autocomplete not working on my search bar?

53 Views Asked by At

I have a search bar that should be visible in all my pages in django, however the autocomplete is not working.

my base.html has the following:

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

this is my search bar:

  <div class="sbar ">
    <div class="row-search ">
        <div class="col-6">
            <form action="{% url 'search' %}" method="get">
                <div class="input-size input-group mb-3">
                  <input type="text" name="q" id="searchBox" class="form-control" placeholder="Search...">
                  <button class="btn btn-primary" type="submit">Search</button>
                  <div id="search-suggestions-dropdown"></div>  <!-- Add this line -->
                </div>
            </form>
        </div>
    </div>
  </div>

this is my script inside my base.html:

<script>
    $(document).ready(function(){
        $('#searchBox').autocomplete({
            source: function(request, response) {
                console.log("Making AJAX request with query:", request.term);
                $.ajax({
                    url: "{% url 'search' %}",
                    dataType: 'json',
                    data: {
                        'q': request.term
                    },
                    success: function(data) {
                        console.log("Received data:", data);
                        var suggestions = [];
                        data.forEach(function(item) {
                            suggestions.push({
                                label: item.label,
                                value: item.value
                            });
                        });
                        response(suggestions);
                    }
                });
            },
            minLength: 2,
            select: function(event, ui) {
                console.log("Selected item:", ui.item);
                window.location.href = ui.item.value;
            }
        });
    });
  </script>

this is from my views.py:

class SearchView(View):
    def get(self, request, *args, **kwargs):
        query = request.GET.get('q')
        print("Received query:", query)  # Print the received query
        if query:
            infos = Info.objects.filter(Q(firstName__icontains=query) | Q(
                middleName__icontains=query) | Q(lastName__icontains=query))
            files = Files.objects.filter(fileName__icontains=query)
            results = list(infos.values('firstName', 'middleName', 'lastName',
                           'orphanID')) + list(files.values('fileName', 'fileID'))
            results = [
                {
                    'label': item['firstName'] + ' ' + item['middleName'] + ' ' + item['lastName'] if 'firstName' in item else item['fileName'],
                    'value': item['firstName'] + ' ' + item['middleName'] + ' ' + item['lastName'] if 'firstName' in item else item['fileName'],
                }
                for item in results
            ]
            print("Infos:", infos)
            print("Files:", files)
            print("Results:", results)
            return JsonResponse(results, safe=False)
        print("No query received")  # Print a message when no query is received
        return JsonResponse({}, status=400)

this is my test.html:

<!DOCTYPE html>
<html>
<head>
    <title>Test Search Bar</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
    <form action="#" method="get">
        <div class="input-group mb-3">
            <input type="text" name="q" id="searchBox" class="form-control" placeholder="Search...">
            <button class="btn btn-primary" type="submit">Search</button>
        </div>
    </form>

    <script>
    $(document).ready(function(){
        $('#searchBox').on('click', function() {
            console.log("Search bar clicked");
        });

        $('#searchBox').autocomplete({
            source: function(request, response) {
                console.log("Making AJAX request with query:", request.term);
                // Mock AJAX request
                setTimeout(function() {
                    var data = [
                        { label: "Result 1", value: "Result 1" },
                        { label: "Result 2", value: "Result 2" }
                    ];
                    console.log("Received data:", data);
                    var suggestions = [];
                    data.forEach(function(item) {
                        suggestions.push({
                            label: item.label,
                            value: item.value
                        });
                    });
                    response(suggestions);
                }, 1000);
            },
            minLength: 2,
            select: function(event, ui) {
                console.log("Selected item:", ui.item);
                // Prevent the form from being submitted
                event.preventDefault();
            }
        });
    });
    </script>
</body>
</html>

Can someone tell me where the error is? There are already console print statements but they do not show up when i type in the search bar. I tried a test.html and the autocomplete is working there. I want to be able to search thru my models using the searchbox.

0

There are 0 best solutions below