Creating a dynamic search bar using Ajax with support for multiple keywords

I recently attempted to create an ajax search bar for my website. It functions perfectly with a single keyword, however, I'm facing some difficulty when trying to make it work with two keywords. I thought about parsing the data in the input field, but due to my limited knowledge, I haven't been able to find a solution. Do any of you have any ideas on how to tackle this issue?

In the main.js file, I'm retrieving the data from the input as shown below:

var kwVal = $(this).val();
if (kwVal.length < 3){
    $(".clothes-container").html("");
}
else {
    $.ajax({
        "url": "ajax/getclothes.php",
        "type": "GET",
        "data": {
            "kw": kwVal 
        }
    })

Here is my SQL query:

$sql = "SELECT title, description, picture
    FROM outfit 
    WHERE type LIKE :keyword OR
          color LIKE :keyword OR
          brand LIKE :keyword OR
          material LIKE :keyword";

Thank you in advance for any assistance you can provide.

Answer №1

Do you think something along these lines? Definitely, make sure to properly escape all SQL literals and strings, especially the $keyword.

// Grabbing keywords from user input
$keywords = array('red', 'shoes');

// Specifying columns to match against
$columns = array('type', 'color', 'brand', 'material');

// Creating conditions for each keyword
$word_conditions = array();
foreach ($keywords as $keyword) {

    $conditions = array();
    foreach ($columns as $column)
        $conditions[] = $column.' LIKE \'%'.$keyword.'%\'';

    $word_conditions[] = '('.implode(' OR ', $conditions).')';
}

// Crafting the query to require all keywords for each item
$query = 'SELECT * FROM ... WHERE '.implode(' AND ', $word_conditions);

Answer №2

If your keywords are separated by spaces, for example, "ABC DEF GEH."

Then, on the server side, you can do the following:

$keywords = explode(" ", $_POST['data']); // Convert to array
$string = implode(",", $keywords);

$sql = "SELECT title, description, picture
    FROM outfit 
    WHERE type in (".$string.") OR
          color in (".$string.") OR
          brand in (".$string.") OR
          material in (".$string.")";

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

CSS translation animation fails to execute successfully if the parent element is visible

Inquiries similar to this and this have been explored, but do not provide a solution for this particular scenario. The objective is to smoothly slide a menu onto the screen using CSS translation when its parent is displayed. However, the current issue is ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

What could be causing my mongoose array to remain empty without any values being stored in it?

Issue at Hand While I have come across several similar problems on Stack Overflow about this particular issue, none of the solutions provided seemed to work for me. I am in the process of developing a basic Forum application with two routes - one for cre ...

What strategies can be implemented to transform a lengthy if-else statement into a more optimized

I have a piece of code where I am setting the status of two scope variables based on an AND operation. Depending on the key, I call the relevant method. The only difference between the two methods is checking prop3. I believe the code is quite redundant ...

Comparing the size of a MongoDB array to another field in a document: how can it be done?

Need guidance on querying MongoDB for documents that have a specific number of users in them. This needs to be done through both the mongo console and JavaScript in Node.js: db.turnys.find( { users:{$size:seats } } ) The structure of turnydb.turnys colle ...

Issue at hand: Unexpected error 500 encountered while sending AJAX request to PHP script through

UPDATE: Issue Resolved! I want to extend my gratitude to everyone who directed me to the error log files for assistance. The community here is truly incredible and I was able to get a resolution much quicker than anticipated. It's quite embarrassing, ...

The instance is referencing "greet" during render, but it is not defined as a property or method

At the same time, I encountered another error stating "Invalid handler for event 'click'". <template> <div id="example-2"> <!-- `greet` is the name of a method defined below --> <button v-on:cli ...

Optimizing the If operator in JavaScript to function efficiently without causing the page to reload

While delving into jQuery and attempting to create a slider, I encountered a problem. After the slider passed through the images for the second time, the first image would not appear. My approach involved using margin-left to move the images. $(document ...

Troubleshooting: AngularJS - Issues with nested controllers not functioning properly within ng-include

According to the AngularJS documentation (refer to nested controller fragment), I am attempting to implement nested controllers using ng-include Main.html <body id="spaWrapperApp" ng-app="spaWrapperApp"> <div class="container-fluid" id=" ...

What is the process for sending a data response with express?

Seeking guidance on running the .get operation on a JSON file I have stored at the path /scripts/src/data/*.json. When making the request, I am setting the headers but unsure how to retrieve the resulting data or where to view this request. Any assistance ...

Front-end procedural logic for increasing identification values

$scope.items.push({ "itemId": $scope.tabId + 1, "itemName" : itemName, }); Whenever I try to push the item, I always console.log($scope.itemId) but it remains the same without increasing. One way to handle this issue could be utilizing $http after each ...

Guide on sending a post request to a PHP component

var table = $('#accessRequest').DataTable({ "dom": 'Blfrtip', "ajax": "Editor-PHP-1.5.1/php/editor-serverside.php", "columns": [ { //special column for detail view ...

Child component in Angular fails to detect input changes

Hey there! I'm currently utilizing parent-child communication in my Angular project. In the parent component, I have an array that represents graph data. If you'd like to check out a demo of what I'm working on, feel free to click here. The ...

Creating route paths within a single .js file

I'm a beginner when it comes to Node/Express, and I have a question about my app structure. Here is a simplified version of how my app is set up: /app /routes filter.js index.js app.js In my app.js file, I have defined my routes like th ...

Turn off link preview feature on Android messages

As a developer, I am looking for a way to disable or hide link previews on Android devices when someone receives a text message with a link to our website. I still want the URL address to be visible, but I prefer to keep the link previews on IOS devices. I ...

Navigating a local and server environment with relative paths in a web server's multiple sites

My ASP.NET website is published to a web server with multiple sites, such as www.example.com/SiteA or www.example.com/SiteB. Before publishing, I test the site locally at localhost:12345. When referencing an image path like /Images/exampleImage.gif, it wo ...

Can someone please provide me with the correct syntax for a jQuery AJAX PUT request that is JSON encoded?

Here is the ajax PUT request that I have written: jQuery.ajax({ url: url_lab_data+"backend/read/{\"f_anid\":"+anid+"}", type: "PUT", data: JSON.stringify({"read": 1}), ...

Changes made to the V-model property will only be reflected after the page is refreshed

I have encountered a situation with two checkboxes that need to reflect the values of watched computed properties. While I can observe reactive changes in my Vue extension when these properties are altered, the updated states of the checkboxes only appear ...

Detection of NTLM error during the parsing of the Authorization header

After posting a question here, I discovered that the issue causing the error was not related to my axios request. Unfortunately, I'm unsure how to close the question. An error occurs when attempting to send an Axios Get request to my express backend ...

Using jQuery to apply CSS to elements with multiple potential values

Here's a simple question: using jQuery's css function, you can retrieve the computed style of a CSS attribute. But what if there are multiple styles for that attribute being rendered simultaneously? Let's consider this example: <div id=" ...