Having Trouble with Jquery UI Autocomplete and JSON Integration

Hi everyone, I'm currently investigating why the autocomplete() method is not performing a GET request when I append a variable to the end of the source URL. Here's an example:

    <script> 
    $(document).ready(function(){
        var search_input;

        $('#search').keyup(function(){
            search_input = ($(this).val());
            console.log(search_input);
        });
        $('#search').autocomplete({
          source: "http://192.168.33.10/app_dev.php/search/query/" + search_input,
          minLength: 2
        });
    });
    </script>

    <div class="ui-widget">
        <label for="search">Search</label>
        <input type="text" id="search" />
    </div>   

However, if I omit the + search_input from the source URL, the GET request works as expected, like this:

    <script> 
    $(document).ready(function(){
        var search_input;

        $('#search').keyup(function(){
            search_input = ($(this).val());
            console.log(search_input);
        });
        $('#search').autocomplete({
          source: "http://192.168.33.10/app_dev.php/search/query/",
          minLength: 2
        });
    });
    </script>

    <div class="ui-widget">
        <label for="search">Search</label>
        <input type="text" id="search" />
    </div>   

Answer №1

To implement the autocomplete function in your code, all you need to do is provide the source parameter with a callback function:

source: function( request, response ) {}

You can refer to the example for Multiple remote suggestions on jQuery UI Autocomplete

    <script type="text/javascript>
      $(function() {
    function split( val ) {
      return val.split( /,\s*/ );
    }
   // rest of the script remains same
});
        </script>

<p>The JSON response from the server in this scenario will look like this:</p>

<pre><code>[{"id":"1544","label":"Suggestion 1","value":"Suggestion 1"},
{"id":"3321","label":"Suggestion 2","value":"Suggestion 2"}]

Answer №2

While you're updating the search_input, keep in mind that the widget will only fetch the URL using the original value of search_input (which is likely empty).

To fix this issue, consider implementing something along these lines:

$('#search').autocomplete({
    source: function (request, response) {
        $.get("http://192.168.33.10/app_dev.php/search/query/" + request.term, response)
    },
    minLength: 2
});

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

Send an AJAX request to redirect to a different page on a PHP server

After collecting data from JavaScript, my page transfers it to PHP and then MySQL. The issue arises when I want the page to redirect to different pages based on the database content. I attempted to use the header function, but it only displayed the entire ...

Is there a way to retrieve data from my JSON file located in the public folder within Next.js 13.3?

My current challenge involves retrieving JSON data from the public folder. async function fetchData() { try { const response = await fetch('/data.json'); const jsonData = await response.json(); return jsonData; } catch (error) { ...

Tips for presenting SVG symbols using Interpolation within Angular 7 from a JSON document

When it comes to displaying content in Angular 7 components, JSON is used. However, I have encountered a problem while trying to incorporate SVG icons from our UX team into the component using JSON. Using the img tag restricts me from applying a CSS class ...

Mapping objects with nested objects using ObjectMapper

I'm facing an issue with mapping a JSON response that contains an array. The mapping process is throwing an error, and I need help on how to handle this type of JSON structure. { "total":10, "count":10, "start":0, " ...

The thickness of the line on the Google line chart is starting to decrease

Currently, I am utilizing a Google line chart in my application. However, I have noticed that for the first two data points, the lineWidth is thick, while for the last two points it is very thin. How can I resolve this issue and ensure that the lineWidth r ...

I'm wondering why this isn't working properly and not displaying the closing form tag

What could be the reason for this not functioning properly? The tag appears to close on its own and the closed tag is not being displayed. As a result, the if(isset($_POST['payoneer-btn'])) statement is not triggering. https://i.stack.imgur.com/ ...

How can I protect my jQuery script from being accessed by "FIREBUG"?

I was tasked with creating a jQuery script as follows: function DeleteFile(_FileID) { //ajax method to delete the file } The FileID is stored in the 'rel' attribute of the list. However, when I call "DeleteFile" from Firebug using the fileId ...

Tips for creating sliding header content alongside the header

Is it possible for the content in the header to scroll up, displaying only the navigation list and hiding the logo when a user scrolls on the website? Currently, while the header background slides up, the content within the header remains in place. I feel ...

What is the best way to extract all the values from this Json in order to perform an Assertion

As I work with a JSON response received as a string, my aim is to create a versatile Assertion method for verifying if a property name matches the correct value. However, extracting the entire JSON data has proven challenging, as only the first set appears ...

Methods for Hiding and Revealing a UIView with the Press of a Single UIBarButtonItem

In my iOS app, I have created a right bar button item programmatically and added it to my view controller. Additionally, I have also added a UIView to the view controller. The action for my bar button item has been set. Currently, the UIView is hidden when ...

Issue with Jackson serialization in @ManyToMany association

I am currently facing the following scenario: //--class user -- private .... @OneToMany(targetEntity = UserRoles.class, mappedBy = "iduser", fetch = FetchType.LAZY) @JsonManagedReference private List<UserRoles> userRoleList = new ArrayList<>( ...

Steps for assigning innerHTML values to elements within a cloned div

Currently, I am setting up a search form and I require dynamically created divs to display the search results. The approach I am taking involves: Creating the necessary HTML elements. Cloning the structure for each result and updating the content of ...

Adjust the number of columns displayed when rendering with Datatables

I've utilized DataTables to create a dynamic datatable. $('table').DataTable( { dom: 'Bfrtip', buttons: [ 'copy', 'excel', 'print', ], responsive: true } The table I created c ...

posting data and redirecting fails when using an ajax button

I am encountering an issue where I click a button on a page to navigate to another page with posted data, but it is redirecting without posting anything. Both $_POST and $_SESSION variables are empty. Below is my ajax function: function ajax4(Div_Submit, ...

Streamline your Salesforce application by automating drop down selections with XPath using Selenium WebDriver

https://i.stack.imgur.com/Eg9jc.pngAn application has been developed in Salesforce with a dropdown box containing items built using the <li> tag. However, I am unsure how to select a specific item from this design. <div id="Department__cformContr ...

How can I initiate a TextChange event in ASP.NET C# without losing focus?

I attempted to trigger the TextChange event using Ajax, but it doesn't seem to be working as I expected. I'm hoping someone here can lend a hand. <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> ...

What is preventing me from retrieving the values of selected options in jQuery when clicking on an option?

I have a select menu with the following options. <select name="assigneeSelect" id="{{this.commonID}}" class="custom-select sources" key="{{this.id}}" placeholder="{{this.assignee}}"> <option v ...

Menu only appears with a double click on the label button

Currently, I'm facing an issue where I have to click the label "button" (hamburger menu) twice in order to show the menu for the second time. My belief is that there might be a conflict between CSS and jQuery causing this behavior. The desired funct ...

How can we use JavaScript to retrieve an element with custom styling?

I've encountered a strange issue with my script where it seems to stack up borders and display a 2px border instead of the intended 1px border when switching elements on click. Here is the link code I am using: <li ><a href="plumbing.php"&g ...

Adding a JSON array to a ListView

I am new to Java programming language, so please forgive any obvious or silly mistakes I may have made. I am working on an activity in which I retrieve a JSON encoded string from a PHP file and display it in a simple list view. However, I am encountering ...