Utilizing Jquery Autocomplete with multiple arrays for data sourcing

I am facing a challenge where I want to display both doctors and their connections in an autocomplete search using jQuery. Although I have successfully displayed the doctors, I'm struggling to categorize and display data from both arrays separately under doctor and connection headings. The JSON returned from the server is structured like this:

    {"connections":
    [{"ConnectionID":"8","ConnectionName":"Saima Fayyaz","ImageName":"201304061217391.5x1.5.jpg"}],
    "doctors":
[{"DoctorID":"4","DoctorName":"Imran Saeed Ali","ImageName":"20130516210722ImranSAli.jpg","Type":"Doctor"},
{"DoctorID":"8","DoctorName":"Saima Fayyaz","ImageName":"201304061217391.5x1.5.jpg","Type":"Doctor"},
{"DoctorID":"10","DoctorName":"Sabira  Javaid","ImageName":"20130406123414123.jpg","Type":"Doctor"}]}

My JavaScript code snippet for the autocomplete functionality is as follows:

<script type= "text/javascript">
$(document).ready(function () {

    $("#people").autocomplete({
        minLength: 0,
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("Search","SearchPathologist")',
                dataType: "json",
                data: {
                    term: request.term,
                    flag: "all"
                },
                success: function (data) {
                    //alert(data.doctors);
                    response($.map(data.doctors, function (item) {
                        // alert(item.Type);
                        return {
                            //data: item.doctors
                              id: item.DoctorID,
                              name: item.DoctorName,
                              photo: item.ImageName,

                        }
                    }));

                }
            });
        },
        focus: function (event, ui) {

        }

    })
.data("autocomplete")._renderItem = function (ul, item) {

    return $("<li></li>")
    .data("item.autocomplete", item)
    .append("<div style='width:100%; margin:auto; background:white; min-height:20px;'><div style='border-bottom:1px dashed gray;'><div style='float:left;  width:16%; min-height:35px; margin:auto;'><img src='http://olivecliq.com:84/carepoint/doctor_images/"+item.photo+"' width='31px' style='margin-top:4px; margin-left:1px;' /></div><div class='mid_card'><h2> " + item.name + "</h2><h3>Use StrongVPN &amp; have a USA or UK IP address anywhere.</h3></div><div style='float:left;width:10%; min-height:25px; margin:auto;'> <img src='@Url.Content("~/images/arrow.png")' width='25' style='margin-top: 10px;' /></div><div style='clear:both;'></div></div>")
    .appendTo(ul);


});

Any assistance on how to handle this situation would be highly appreciated.

Answer №1

To overcome the issue, I implemented a similar solution.

Below is the jQuery code utilized:

<script type="text/javascript">
$(document).ready(function () {
    var drew = false;
    $("#people").on("keyup", function (event) 
    {
        var query = $("#people").val();

        if ($("#people").val().length >= 1) 
        {
            $('div#loaderContainer').show();
            $.ajax({
                url: '@Url.Action("Search","SearchPathologist")',
                dataType: "json",
                data:
                    {
                        term: query,
                        flag: "all"
                    },
                    error: function()
                    {
                    $.fallr('show', {
        content: '<p>An error occurred! Your session may have expired.</p>'
                    });
                    },
                success: function (data) 
                {
                    $('div#loaderContainer').hide();

                        if (drew == false) 
                        {
                            $("#people").after("<ul id='res' class='ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all' role='listbox' aria-activedescendant='ui-active-menuitem' style='z-index: 10005; display: block; width: 293px;'></ul>");
        
                            drew = true;

                            $("#res").on("click", "li.item", function () 
                            {
                                $("#people").val($(this).text());
                                $("#res").empty();
                            });
                        }
                        
                        else 
                        {
                            $("#res").empty();
                        }

                        $.each(data.doctors, function (i, item) {
                            // Code omitted for brevity
                        });

                        $.each(data.connections, function (i, item) {
                            // Code omitted for brevity
                        });

                    if($('button#searchDDL').html() == "Doctors")
                    {
                    $('div#connections').hide();
                    }
                    if($('button#searchDDL').html() == "Connections")
                   {
                   $('div#doctors').hide();
                   }

                }


            });
        }

        else
        {
        $("#res").empty();
        $( "#res" ).remove();
        drew = false;
        }
    });

    $("input#people").focusout(function () {

$( "#res" ).remove();
drew = false;
});
});

</script>

The HTML used is as follows:

 <div class="search_input"><input type="text" id="people" placeholder="Search for specialist doctors and more.." />
</div>
<button type="submit" class="search-button" value="Search" name="search">
        <span><img src="@Url.Content("~/images/search-icon.png")" height="20" /></span>
      </button>
</div>

Moreover, the action taken is described below:

public JsonResult Search(string term, string flag)
{
// Code implementation here
}

WCF Service method utilized:

public SearchResult Search(string PersonID,string term,string flag)
{
// Code implementation here
}

Defined classes like SearchResult, Doctor, and Connection:

// Class definitions

Tutorial post on this implementation available at:

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

How can you fetch data from a PHP file using AJAX before performing a header redirect?

I am currently in the process of adding more dynamism to my website. I have developed a forum from scratch and now I am integrating JavaScript into it. All the PHP backend work is complete. My next goal is to enable user login without having to refresh the ...

Trouble with Ajax Request in HTML

I encountered an error while running the following code, where it directly goes to "Ajax Failed" with the error message [Reference Error: Ajax Failed is not defined]. Can someone please point out where I went wrong? This code involves base 64 encoding valu ...

Combine all possible pairings of elements from two distinct arrays

Is there a way to combine the elements of two arrays and return them in a new array? Let's say we have these two arrays: const whoArr = ["my", "your"]; const credentialArr = ["name", "age", "gender" ...

The server response value is not appearing in Angular 5

It appears that my client is unable to capture the response data from the server and display it. Below is the code for my component: export class MyComponent implements OnInit { data: string; constructor(private myService: MyService) {} ngOnInit ...

Postman is displaying [object object] as the return value, but the actual value is not

Currently, I am working on automating tasks using Postman One interesting aspect is the presence of a vehicles array in the body { "Vehicles":[ { "car":"{{car}}", "bike":"{{bike}}&quo ...

combine two 2D arrays in JavaScript

I am facing a challenge with this issue concerning 2D arrays. The task at hand is to create a JavaScript function called addArrays(al, a2) that accepts two 2D arrays of numbers, a1 and a2, and calculates their "sum" following the matrix sum concept. In oth ...

What is the process for altering a route in React 18?

Previously, I relied on the withRouter Higher Order Component (HOC) along with props.history.push() function to manage routes. However, with the introduction of React 18, these options are no longer available. My current task involves editing a post and ...

React to the animated scaling

I'm attempting to animate the scale of my react component. Although it seems straightforward, I've run into some issues while following a similar example from the React-Motion demos: var customComponent = () => { let newStyle = { scale: sprin ...

Utilize Flutter to implement a json.decode function that can transform a String into a usable format for display in the user interface

Although it may seem like a simple query, I am struggling to find the solution. Within my app, there are 2 screens. The first screen contains just one button: onPressed: () { fetchCurrentTitle(); Navigator.push(context, MaterialPageR ...

How can I eliminate the repeated elements in a JSP JAVA array table?

I am dealing with two arrays: <%String TXTfileArray[] = (String[])request.getAttribute("txt");%> <%String TXTContentArray[] = (String[])request.getAttribute("content");%> There is repeated data in these arrays. I have a statement in my JS ...

Replace the phrase "add to cart" with "plus" and "minus" in Opencart

I am trying to customize the Add to Cart functionality in OpenCart 2.0.1.1 by replacing it with plus and minus buttons. I have successfully added the plus button, however, I am facing difficulty coding for the minus button. The code snippet below shows w ...

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...

Using handlebars template to render multiple objects in MongoDB with node.js and mongoskin

Dealing with an application that requires reading from two different collections in a Mongo database and passing the returned objects into a handlebars template has been quite a challenge for me. The code snippet I've been working with doesn't s ...

Can this be executed in PHP?

Can this code snippet work in PHP? foreach (function() { return ['key' => 'Value']; } as $key => $val){ $new_array = array('Key' => $key, 'Value' => $val); } I am interested in mo ...

Converting JSON to CSV using JQ command in Linux shell

Seeking to convert a JSON into a CSV file where each Line Item Object is on a separate line, and that line includes the PURCHASEORDERNO. Attempting to retrieve the PURCHASEORDERNO of the HEADER array from the LINE ARRAY using .HEADER[].PURCHASEORDERNO. En ...

Entry Points for Logging In

After stumbling upon this pre-styled Material UI login page example, I decided that it was exactly what I needed. However, I ran into an issue when trying to figure out how to store the username and password values. Whenever I try to use 'State' ...

Using web3Provider in a Next.js environment

While attempting to integrate Web3-react v6 into my Next JS project, I encountered an error when trying to wrap my entire app with the provider. In _app.jsx, I included the following code: import React from 'react'; import { Web3ReactProvider } ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

Getting the directory path from JSON using Python

Received an API response in JSON format: "files":[ { "name":"main", "node_type":"directory", "files":[ { "name":"source1", "node_type":"directory", "files":[ { "name ...

Steps for implementing a Toggle Navigation Bar in CSS

I'm looking to implement a show/hide navigation menu similar to the one showcased in this inspiration source: Code Snippet (HTML) <div id="menus"> <nav id="nav"> <ul> <li><a href="#">HOME</a></li> <li& ...