Exploring the inner workings of a JSON with Ajax and PHP

I'm working on a project that involves a JSON file called items.json. My goal is to create a search box where users can input either the name of an item or its category, and see live search results as they type. Here's what I’m aiming for:

If someone searches for "AXE," the search should display all items that start with “AXE” as soon as they start typing. If the user searches for "Hygene," it should list all products under that category.

Essentially, I want to implement an HTML field with live search functionality that pulls data from a JSON file using Ajax. It would be ideal if PHP could also be incorporated into this solution.

[
    {
        "product": "132431",
        "productName": "AXE Body Spray",
        "categoryName": "Hygene"
    },
]

If anyone has any suggestions, I would greatly appreciate your help. I struggle with this aspect of development, so the more detailed and specific the advice, the better.

Any guidance on implementing something like this: or jQuery Autocomplete would be very helpful. I’ve spent countless hours going through documentation, but I keep running into issues due to my lack of experience.

Answer №1

For optimal performance, it is recommended to conduct the search on the client side without the need for a plugin if your data is relatively simple. Below is a functional example in Javascript that you can customize:

var CustomSearch = {

    Items : [   {   "product": "132431",
                    "productName": "AXE Body Spray 1",
                    "categoryName": "Hygene"
                },
                {   "product": "132432",
                    "productName": "AXE Body Spray 2",
                    "categoryName": "Hygene"
                },
                {   "product": "132433",
                    "productName": "AXE Body Spray 3",
                    "categoryName": "Hygene"
                },
                {   "product": "11",
                    "productName": "Bacon",
                    "categoryName": "Food"
                },
                {   "product": "12",
                    "productName": "Eggs",
                    "categoryName": "Food"
                },
                {   "product": "9",
                    "productName": "Beer",
                    "categoryName": "Beverages"
                }
            ],


    searchProduct: function(search) {
        var foundItems = $.grep(CustomSearch.Items, function(value, index) {
                        return value.productName.substring(0, search.length) == search;
                    });
        CustomSearch.printResults(foundItems);
    },


    searchCategory: function(search) {
        var foundItems = $.grep(CustomSearch.Items, function(value, index) {
                        return value.categoryName.substring(0, search.lenght) == search;
                    });
        CustomSearch.printResults(foundItems);
    },


    printResults: function(foundItems)  {
        var output = "";  
        $.each(foundItems, function(key, item) {
            output += "<option>" + item.productName + "</option>\n";
        });
        alert(output);
    }

};

You can try it out with:

CustomSearch.searchProduct("AXE");
or
CustomSearch.searchCategory("Food");
. Best of luck!

Answer №2

Here is a helpful resource for using PHP to implement AJAX live search functionality: . (Alternatively, you can search on Google for: "php autocomplete ajax") Best of luck!

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

The Vue.js error message "Unable to access property 'array_name' as it is undefined" indicates an issue with

I'm currently working on fetching data using Axios requests and storing it in an array. Below is the code I have been using: props: [ 'products', ], data: function () { return { algolia: '', pro ...

Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I ...

I am attempting to access data through an ajax function, but it is not functioning correctly

When working with asp.net webform, I encountered an issue while trying to call data using an ajax call. Although a similar function on another page works without errors, on this particular page, I am facing an error. The error I am getting is pageCountInt ...

Unable to insert a JSON object into an Array

This might appear to be a duplicate, but it's not. None of the solutions I've tried have worked. Within my angular module, I have a list: this.checkedInterviews = [] Followed by a function that does the following: var interviewModel = { ...

What is the reason for multiple ajax functions being triggered when submitting a form through ajax?

I have a Drupal form with an AJAX submit. Additionally, I have another jQuery $.get function that sends a request every 2 minutes and inserts the response into an HTML element. The form and this JavaScript code are independent of each other, performing sep ...

The functionality of the Vueify modal seems to be malfunctioning when incorporating Vueify alongside a central Modal.vue file that houses modal templates

I've been experimenting with integrating this tutorial on creating reusable modal dialogs with Vuejs and adapting it for use with Vueify. Initially, I was able to successfully implement it, but after exploring a different approach briefly, I returned ...

setting a callback function as a variable

I have encountered an issue where I am passing a callback function but unable to call it when the onreadystatechange changes its value, specifically request.onreadystatechange = func. Even though I receive a response from the server when making the ajax ...

Fluctuating updated site (ajax)

What method do you recommend for maintaining the data in a table on a page current? Currently, I am using a timer that connects to the server via ajax every 2 seconds to check for updates. Is there a way to trigger an event or function only when the cont ...

Upon opening index.html in the browser, the jQuery code fails to execute, as no errors are displayed in the console

I am struggling to make a simple toggleClass() function work in jQuery and I can't seem to figure out why. This is just a beginner exercise for me with jQuery. The code works perfectly when I test it as a snippet or manually in the console, but when I ...

invoking a boolean type JavaScript function

I'm currently working on calling a Page Method using AJAX. Take a look at the code below: <asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" Text="Upload" onclick="btn_upload_Click" OnClientClick="return Validate();" /> ...

I have encountered an issue where after declaring a JavaScript variable on a specific page, including the JavaScript file does not grant access to it

<script type="text/javascript"> $(document).ready(function () { var SOME_ID= 234; }); </script> <script type="text/javascript" src="<%= HtmlExtension.ScriptFile("~/somefile.js") %>"></script> ...

Looping through a single object with an Ajax call

When I make this ajax call, it only displays the last object from the JSON file instead of all objects. Can someone help me understand why? Ajax Call var ajax = new XMLHttpRequest(); var data = 'data.json'; var url = 'http://localhost: ...

Issues arise when attempting to send an AJAX POST request within WordPress

After going through multiple resources, all mentioning the same approach that I am following, I have two essential files for this process: In the receiver.php file: <?php add_action( 'wp_enqueue_scripts', 'my_enqueue' ); ad ...

I need to change a website into a string so that I can analyze it with javascript. How can I do this?

Currently, I am in the process of creating a website for my video game servers. The admin tool we use outputs the current server status in a .json format as a large text string to this specific URL: My goal is to retrieve the entire text string from the p ...

When does JSON overload become a problem?

Creating a bookmarking site similar to delicious has been my latest project. To ensure an optimized user experience, I have decided to fetch all the bookmarks from the database table and organize them into a JSON object containing essential data such as id ...

Can Comet be implemented without utilizing PrototypeJs?

Can Comet be implemented without utilizing PrototypeJs? ...

Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue. I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help. The challenge I f ...

Can you provide some insight on how to store XMLHttpRequest response in Javascript for future

I have a function in my codebase that is responsible for loading HTML templates asynchronously: loadTemplate: function(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open("GET" ...

Is there a way to properly structure the json data displayed in my network tab on Chrome?

After sending an http request to my backend, I received a json response in the network tab. However, the format of the json is unreadable. To clarify, here is a screenshot: https://i.stack.imgur.com/RBiTd.png Currently using Chrome, I am seeking assistanc ...

Clicking outside the div will cause the div to be hidden

Looking for some help with a jQuery issue. I have a pop-up that opens when a div is clicked, but I want it to close when clicking outside of the div instead of just on the close button. <a class="close-up" href="#" onclick="popup('popUpDiv')" ...