The search bar in Laravel is encountering an Uncaught ReferenceError with AJAX

I'm attempting to create a real-time search bar for my products list, but I keep encountering an error in my console

Uncaught ReferenceError: data is not defined
at HTMLInputElement.<anonymous> (produits:243)
at HTMLDocument.dispatch (jquery-2.2.4.min.js:3)
at HTMLDocument.r.handle (jquery-2.2.4.min.js:3)

I want to show the products without refreshing the page, which is why I opted for ajax. However, as I have only used it once, I am struggling to grasp every part of this code I discovered. Here is my blade:

<div class="view-product d-flex align-items-center mr-15">
                        <input type="text" placeholder='...' class="form-check" id="keyword" name="keyword" title="search product">
                        <p><i class="fa fa-search mr-15" ></i></p>
                        <div id="result">

                        </div>
                    </div>

Here is my script

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script>
    $(document).ready(function(){
        fetch_customer_data();
        function fetch_customer_data(query = '')
        {
        $.ajax({
        url:"{{ route('search') }}",
        method:'GET',
        data: {query: query},
        dataType:'json',
        success: function(data) {
            if (data.success) {
                $('#result').html(data.html);
            } else {
                console.log(data.message);
            }
            }
        })
        }
        $(document).on('keyup', '#keyword', function(){
        var query = $(this).val();

        fetch_customer_data(query);
        $('#result').html(data.html);
        $e.preventDefault();
        });
    });
</script>

And finally, here is my controller

if($request->ajax()) {
            $query = $request->get('query');

            if(empty($query)) {
                return back()->withError('No results found');
             }
            else {
                $products = DB::table('products')
                ->where('product_name','LIKE','%'.$request->keyword."%")
                ->where('description','LIKE','%'.$request->keyword."%")
                ->where('activity_type','LIKE','%'.$request->keyword."%")
                ->get();
            }
            $total = $products->count();

            $html = view('front.search_result', [
                'products' => $products,
            ])->render();

            return response()->json([
                'success' => true,
                'html' => $html,
                'total' => $total,
            ], 200);
        } else {
            return response()->json([
                'success' => false,
                'message' => "Something went wrong!",
            ], 403);
        }

What could be the issue with my code?

Answer №1

Within your event handler for the keyup function, you are redundantly calling $('#result').html(data.html); since it is already being done in the ajax request. Please consider removing this line from your code.
Additionally, you are utilizing a variable $e as an event object without defining it anywhere.

$(document).on('keyup', '#keyword', function($e){ // define event parameter
    var query = $(this).val();

    fetch_customer_data(query);
    //$('#result').html(data.html); remove this line
    $e.preventDefault();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using elegant query to group by month and calculate the count of each unique value

I'm currently working on a query to display the usage of medications by month over the past 6 months for each medication group. The output query should appear as follows: medication | October | September | August | July | June | May 1 ...

Steps for logging into Laravel using both MD5 and Bcrypt hashing concurrently

I am currently working with a database where passwords are stored using MD5 encryption. Now, I need to go through the following steps: 1. User login (using bcrypt) 2. If the login fails, move on to step 3. Otherwise, log in and exit. 3. User login ...

What is the best way to insert a button at the end of the last row in the first column and also at the

I am working on a JavaScript project that involves creating a table. My goal is to dynamically add buttons after the last row of the first column and also at the top of the last column. for (var i = 0; i < responseData.length; i++) { fo ...

The Info Box in Google Maps seems to be ignoring the click event

What's the best method to add a click event to a Google Map? ...

Having trouble getting Jquery Ajax Post to work properly when using JinJa Templating?

Objective: My goal is simple - to click a button and post information to a database. Problem: Unfortunately, clicking the button doesn't seem to be posting to the database as expected. Setup: I am working with Flask Framework, Jquery, and Jinja Temp ...

Axios does not appear to be transmitting cookies

In my development setup, I am using two separate applications: a server-side application built with Laravel and a client-side application using VueJS. The Vue app consumes the API provided by the Laravel app to interact with the backend functionalities. A ...

What is a reliable method to retrieve the text from the current LI if all LI elements in the list share the

I'm encountering an issue with retrieving the text from LI elements because I have 10 list items and they all have the same class name. When I attempt to fetch the text using the class name or id, I only get the text of the last item. Here is my code ...

Can someone assist me in populating my dropdown menu with the data from my JSON response?

I have received JSON data from a C# web method in the following format: {"d":["ADAMS CITY","BOULDER","ANTON","ARBOLES"]} There is an ASP.NET dropdown with the ID #city. After receiving a success alert on my AJAX request, how can I display this data in th ...

Saving a revised JSON file using AngularJS

Currently, I am in the process of developing a phonegap application using AngularJS that relies on a .json file to store an array of entries. The main goal I am aiming for is to enable users to mark specific entries as favorites and then utilize that data ...

Creating an index on a JSON array type in MySQL 5.7 can optimize the performance of your

Currently, I am using an SQL script similar to SELECT * FROM user WHERE JSON_CONTAINS(users, '[1]');. However, this method scans the entire table and is inefficient. I would like to create an index on the users column. For instance, if I have a ...

Modifying the image height in a column using Bootstrap and JSON data

My webpage is dynamically generating images from a JSON file through a JavaScript file. However, the images are displaying at different heights, and I want each column to adjust to the height of the image to eliminate any gaps. Particularly, data with the ...

I need to retrieve a specific image ID from a foreach loop in CodeIgniter using AJAX

I am looking to extract a specific image record from a foreach loop and then pass this value to another page. <?php foreach($portfolio_image as $image):?> <h3><?=$image->portfolio_image_title?></h3> <p><?=$ima ...

When an image is clicked, I am attempting to access data from a Sharepoint list

In my Sharepoint list, there are three columns: Image, Title, and Description. I am using ajax to retrieve the items from the list. The images can be successfully retrieved, but my goal is to display the title and description of the clicked image when an ...

The issue in Vue JS arises when trying to access JSON key values from an object array using v-for

I am currently working on parsing a list of objects found within a JSON payload into a table utilizing Vue.js. My goal is to extract the keys from the initial object in the array and use them as headings for the table. While the code I have in place succe ...

How to correctly serialize nested maps in JQuery ajax data for sending?

var locationData = { "location" : { "name" : $("#user_loc_name").val(), "street_address" : $("#user_loc_street_address").val(), "city" : $("#user_loc_city").val(), "province" : ...

Managing numerous asynchronous requests and subsequent responses

Dealing with numerous ajax responses is my current challenge. It's important to note that each request may vary in completion time. It can be quite tricky when it comes to distinguishing between successful and failed requests. Any tips on how to dete ...

Unable to Validate Ajax Form if Enclosed within <form> Elements

Could you please take a moment to review this link and help me understand why I am unable to validate the form when it is enclosed within a <form> ... </form> tag? Upon examining the code, I noticed that validation works fine when the form is ...

Using the Table-multiple-sort feature in boostrap-table is not functioning properly when there are multiple tables present on a single page

I have implemented bootstrap-table along with the extension table-multiple-sort. The issue I am facing is when I include two tables on a single page (with the second table within a modal window), the multisort feature does not seem to work on the second ta ...

Navigating a JSON object with Coffeescript iteratively

I'm a beginner in Coffeescript and I'm facing a challenge with resolving an issue. Currently, I have a JSON object stored in a variable. Can somebody guide me on how to loop through the keys in the JSON object to show both the key name and its co ...

When attempting to access the requested resource in AngularJS, there is no 'Access-Control-Allow-Origin' header present

When attempting to run my web-service from within my code, I encounter the following error message: "XMLHttpRequest cannot load http://mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:/ ...