How to do jQuery autocomplete using an AJAX call to a PHP script?

纵饮孤独 提交于 2020-01-30 07:52:46

问题


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?


回答1:


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
},


来源:https://stackoverflow.com/questions/36385771/how-to-do-jquery-autocomplete-using-an-ajax-call-to-a-php-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!