如何使用对PHP脚本的AJAX调用来执行jQuery自动完成?

问题描述:

I have the following jQuery code for the autocomplete,

$( "#text" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          type: 'GET',
          url: 'server.php',
          dataType: 'json',
          data: {
            input: request.term
          },
          success: function(data) {
          response( $.map(data, function(item) {
            return {
              label: item.Symbol + " - " + item.Name + " ( " + item.Exchange + " )"
            }
          }));
        }
        });
      },
      minLength: 1,
      select: function( event, ui ) {
           var symbol = ui.item.label.split(' ');
               setTimeout(function() {
                   $('#text').val(symbol[0]);
               },0);
      }
    });

Whenever a user enters a key in the textbox, an AJAX call is made to a PHP file. This PHP file will retrieve data from an API and update the suggestions list for the autocomplete feature?

I've got the following code in the PHP side,

<?php
if(!empty($_GET['term'])) {
        $term = $_GET['term'];
        $url = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=".$term;

        $j_response = file_get_contents($url);
        $j_response = json_decode($j_response);

        print json_encode($j_response);

    }
?>

For some reason, the autocomplete isn't working for me- what am I doing wrong here?

In the PHP, you are trying to use $_GET['term'], but in the JavaScript your variable is called input. Change the data object to use term not input:

data: {
  term: request.term
},