"Enhancing Search Functionality using AJAX in Laravel and Vue: Handling Empty Search

My goal is to create a search feature using AJAX and Vue.

I have a model named "file" which contains all my files.

Next, I created a controller called searchcontroller.php

public function search(Request $request)
{
    $files = File::where('name', $request=>keywords)->get();
    return response()->json($files);
}

This is the route for my search functionality

Route::post('/', 'SearchController@search');

Additionally, I have a search.vue file:

<template>
<div>
    <input type="text" v-model="keywords">
    <ul v-if="results.length > 0">
        <li v-for="result in results" :key="result.id" v-text="result.name"></li>
    </ul>
</div>
</template>
<script>
export default {
    data() {
        return {
            keywords: null,
            results: []
        };
    },

    watch: {
        keywords(after, before) {
            this.fetch();
        }
    },

    methods: {
        fetch() {
            axios.get('/', { params: { keywords: this.keywords } })
                .then(response => this.results = response.data)
                .catch(error => {});
        }

    }

}
</script>

When I type a letter, the response seems to work but it displays an excessive amount of empty list items.

You can see the issue here: https://i.sstatic.net/tsuN8.png

I would like to implement the solution shown in this example: https://jsfiddle.net/hej7L1jy/2/

Upon console logging the results and keywords:

The results show as Array(0)

However, the keyword input appears to be functioning correctly.

Answer №1

function searchQuery(input) {
    let searchTerm = 'name=' + input;

    fetch('https://example.com/search', {
        method: 'POST',
        body: JSON.stringify({ query: searchTerm }),
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
}

searchQuery("keyword");
<template>
<div>
    <input type="text" v-model="query">
    <ul v-if="results.length > 0">
        <li v-for="result in results" :key="result.id">{{ result.name }}</li>
    </ul>
</div>
</template>
<script>
export default {
    data() {
        return {
            query: null,
            results: []
        };
    },

    watch: {
        query(after, before) {
            this.fetch();
        }
    },

    methods: {
        fetch() {
            axios.post('/', { params: { keywords: this.query } })
                .then(response => this.results = response.data)
                .catch(error => {});
        }

    }
}
</script>

Answer №2

Success!

Controller:

public function search(Request $request)
{
    $files = DB::table('files')->where('name', 'like', '%' . $request->get('keywords') . '%')->get();
    return response()->json($files);
}

Route:

Route::get('/search', 'SearchController@search');

Vue:

<template>
<div>
    <input type="text" v-model="keywords">
    <ul v-if="results.length > 0">
        <li v-for="result in results" :key="result.id">{{ result.name }}</li>
    </ul>
</div>

</template>

<script>
    export default {
        data() {
            return {
                keywords: null,
                results: []
            };
        },

        watch: {
            keywords(after, before) {
                this.fetch();
            }
        },

        methods: {
            fetch() {
                axios.get('/search', { params: { keywords: this.keywords } })
                    .then(response => this.results = response.data)
                    .catch(error => {});
            }

        }
    }
    </script>

I modified the where function in my controller and realized I needed a "get" method instead of a "post" :)

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

Having trouble transferring JSON data from JavaScript to Java within a Play framework

function verify() { var data = document.getElementsByName("data"); var length = data.length; var object = 5; var jsonData = JSON.parse(JSON.stringify(object)); $.ajax({ type : 'POST', url : 'http://local ...

Struggles with ASP.NET AJAX Toolkit communication issues

We are currently experiencing issues with a user accessing our site through a 3G connection. Our ASP.NET 2.0 application utilizes the AJAX toolkit updatepanels to display data, but there have been reports of missing elements within the updatepanel. It seem ...

Is there a way to verify if the overflow of an element with a width of 100% has occurred?

Here is the structure I am working with: <div class="card"> <div class="container"> <slot /> </div> </div> The Card element has a fixed width of 33rem. The container within it spans 100% of ...

A Guide on Adding Excel-Like Filtering Functionality to AngularJS

I am struggling to implement a simple Excel-like filter for a table using AngularJS (v.1). I have shared my code snippet below and would appreciate any help to show filtered data in the table after checking a checkbox and clicking on the OK button. I have ...

Click on the form to initiate when the action is set to "javascript:void(0)"

I am working on an HTML step form that needs to be submitted after passing validation and ensuring all fields are filled. The form currently has an action controller called register.php, but also includes action="javascript:void(0);" in the HTML form. What ...

Tips for accessing the individual field values of many documents within a MongoDB collection

Within my collection of documents lies a structured schema: { "_id" : ObjectId("8dcaac2eb104c2133d66f144"), "Shape" : "circle", "Color" : "blue" }, The objective is to dynamically retrieve the value of a specific field for multiple docum ...

Specialized hover mission

Do you have a question? Imagine you have 3 spans where the default color is black. When you hover over a span, its color changes to red. But what if I told you that at the start, the first span has an orange color. Now, I want to hover over the orange on ...

What is the best way to set conditions for document side script?

I'm struggling to disable the horizontal scroll when the viewport width is 480px or less. The script that controls the scroll behavior on my website looks like this: <script> $(function () { $("#wrapper").wrapInner("< ...

How can I pass a PHP variable to a JavaScript variable using PHP and JQuery/JavaScript?

I am facing a challenge with a large <select> input that is used across multiple pages. My idea is to separate this dropdown box into its own PHP file and load it externally using JQuery. Is this approach feasible? Here's an outline of what I ha ...

Ways to conceal the lower details in DataGrid Material-UI

Utilizing the DataGrid component from MUI and I'm eager to conceal this element. Any suggestions on how I can achieve this? Thanks! https://i.sstatic.net/2YG9s.png ...

Is there a way to create a custom column in Tabulator that displays a calculated value for every row?

Can a custom column be added with a calculated value for each row? For example, if col 1 has the value "3" and col 2 has the value "5", then I want a dynamic col 3 with a sum value of 8. I am utilizing Vue Tabulator. Below is my Table.vue component. <t ...

Preview and enlarge images similar to the way Firefox allows you to do

When you view an image in Firefox, it is displayed with the following characteristics: Centered within the browser window. Has a height/width that fits within the browser dimensions. Does not resize larger than its maximum size. Remains the same size if ...

What is the best method for dynamically increasing the data in a shopping cart?

My goal is to stack cart items dynamically every time the addProduct() function is called. I've successfully captured the data, but I'm facing an issue where the quantity always remains at 1 on each function call. Here's the logic I've ...

React Native encountered an issue loading the configuration for your project

I'm having trouble creating a react native app. Every time I run the command "npx react-native init newProject", I encounter an error. Can someone assist me with creating a react native app and troubleshooting the recurring errors? strong texthttps:/ ...

Deleting information from several stores in React Reflux using a single action function

In the AuthActions file, there is a straightforward function called _clear that assigns this.data to undefined. This function is only invoked when a user logs out. However, upon logging back in with a different user, remnants of data from the previous ac ...

Guide to testing express Router routes with unit tests

I recently started learning Node and Express and I'm in the process of writing unit tests for my routes/controllers. To keep things organized, I've split my routes and controllers into separate files. How should I approach testing my routes? con ...

Printing doesn't display CSS styling

I am currently working on creating a function to change the font color, however, I am facing issues with the CSS when it comes to printing. Here is the code I have: $('#draw').on('click', 'p', function () { if($(this).ha ...

Tips for capturing the response during an ajax request?

</html> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script> $.ajax({ type: 'GET', url: 'http://api.twitter.com/1/statuses/retweeted_to_me.json?& ...

The Quirky Behavior of Laravel Queries: Serving Up Varied Results for Ident

Hey there, I've been working on setting up a one-on-one messaging system in Laravel. Everything was running smoothly until some users started experiencing unexpected results. Strangely enough, this issue only seems to affect certain users. Can anyone ...

Are there any techniques in JavaScript to reduce the length of a number?

How can numbers be shortened? For instance, changing 1,000,000 to 1M, 1,000 to 1k, and 10,000 to 10K. ...