0

I'm making an AJAX call with Jquery-autocomplete on a wordpress website (A list of airports as label and the Airport ID as value).

What is returned is an array with both label and ID, but the input is not showing anything as it was when I only returned an single array of names.

The data source :

function ajax_listings() {
global $wpdb; 

//get names of all airports
$name = '%'.$wpdb->esc_like(stripslashes($_POST['name'])).'%';
$sql = "select airportid, completename
    from _airports
    where completename like %s";

$sql = $wpdb->prepare($sql, $name);

$results = $wpdb->get_results($sql);

$titles = array();
foreach( $results as $r ) {
    $titles[] = array(
        "label" => $r->completename,
        "value" => $r->airportid
    );
}

echo json_encode($titles); 

die(); 
}

My AJAX call :

$('#start').autoComplete({
    source: function(name, response) {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'wp-admin/admin-ajax.php',
            data: 'action=get_listing_names&name='+name,
            dataType: 'json',
            success: function( data ) {
              response( $.map( data.d, function( item ) {
                return {
                  label: item.label,
                  value: item.value
                }
              }));
            }
            });
    },
    select: function (event, ui) {
             $('#start').val(ui.item.label); // display the selected text
             $('#idstart').val(ui.item.value); // save selected id to hidden input
             return false;
    },
    focus: function (event, ui) {
        event.preventDefault();
        $(this).val(ui.item.label);
    }
});

I want the text input to only show the label of the items as suggestions, but I also need the airport ID to store in a hidden input and use it later.

An example of array that is returned when I type "MON" :

[101] {label: "PLP, Captain Ramon Xatruch Airport, La Palma, Panama", value: "5841"} 
[102] {label: "LTI, Altai Airport, Altai, Mongolia", value: "6370"}
...
3
  • Not sure what the issue is exactly, but your $.map call doesn't look like it changes anything. It returns exactly what you passed into it. Commented Jan 30, 2019 at 20:07
  • Welcome to Stack Overflow. Based on your JSON that is returned, you should not need to use .map(), the data should already be in the correct Array of Objects format that Autocomplete is looking for. Can you proivide an example of the data that is returned? Commented Jan 30, 2019 at 20:07
  • Hi Twisty. The data returned is an array with this formatting : {label: "PLP, Captain Ramon Xatruch Airport, La Palma, Panama", value: "5841"}. The returned values are correct, but I'm unable to show only the label as autocomplete suggestions. Commented Jan 30, 2019 at 20:26

2 Answers 2

1
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
 <div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags">
  </div>

</body>
<script>
    $( function() {
      var availableTags = [
        { label: "ActionScript", value: "123" },
        { label: "AppleScript", value: "456" },
        { label: "Scheme", value: "Scheme" }
      ];
      $( "#tags" ).autocomplete({
        source: availableTags,
        focus: function(event, ui ) {
          // console.log(ui.item.label);
          this.value = ui.item.label; // this doesn't work
        }

      });
    } );
  </script>
</html>

use and enjoy do comment if helpfull for you copy paste code and use it as your require

Sign up to request clarification or add additional context in comments.

Comments

0

I suspect the issue is here:

data: 'action=get_listing_names&name=' + name,

The variable is name yet UI passes an Object in with this: { term: '' }. Change it to:

data: 'action=get_listing_names&name=' + name.term,

This will provide the text from the input.

Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:

  • A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".

  • A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.

More full example:

$(function() {
  $('#start').autocomplete({
    source: function(req, response) {
      $.ajax({
        type: 'POST',
        dataType: 'json',
        url: 'wp-admin/admin-ajax.php',
        data: 'action=get_listing_names&name=' + req.term,
        dataType: 'json',
        success: function(data) {
          response(data);
        }
      });
    },
    select: function(event, ui) {
      $('#start').val(ui.item.label); // display the selected text
      $('#idstart').val(ui.item.value); // save selected id to hidden input
      return false;
    },
    focus: function(event, ui) {
      event.preventDefault();
      $(this).val(ui.item.label);
    }
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div>
  <label>Start</label> <input type="text" id="start">
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.