How to update a HTML list with jQuery/AJAX JSON data


New Member
I have a list of ~25 items (and potentially more coming), and an input text field, in which the user can type a keyword, upon which the list should be updated to reflect only items that correspond to that keyword.

I would like to use a AJAX call to a PHP file which returns accordingly the results in JSON style.

Being a newbie in that field, having looked at many examples, I am somehow stuck between the AJAX call and the update of the list...

<div id="div_geg">
  <input type="text" name="q2" id="query2" /> 
  <ul name="ul_geg" id="ul_geg">
    <li>item 1</li>
    <li>item 2</li>
// update the list
function updateGEGsList(updated_gegs)
  // clear the existing list
  $('#ul_geg li').remove();

  $.each(updated_gegs, function(index,gegName) {
    $('#ul_geg .list').append("li id='" + gegID + "' style='padding-left: 10px;'><a href='#!' style='color: #3c72d2'>" + gegName + "</a></li>")
AJAX call:
// get data
            type: 'POST',
            url: 'etc/php/autocomplete_mea.php',
            data: 'term=' + $("#query2").val(),
            dataType: "json",
            success: function(response) {

In principal, the PHP file being called sends the correct results back. Tried that out.

My first issue is, that the call is not working properly. I receive a "Uncaught ReferenceError: data is not defined" upon typing into the input field.

Secondly, for the update of the list, the AJAX-return is an array of {ID, NAME}, and I am not sure how this can be implemented.
[{"id":"11","value":"Aichi Biodiversity Targets"},
{"id":"8","value":"Aichi Biodiversity Targets"},
{"id":"19","value":"Joint Convention on the Safety of Spent Fuel Management and on the Safety of Radioactive Waste Management"}]
Thanks a lot for any hints!


Thành viên BQT
In your ajax callback, you get a response variable, but, you pass data to your update function, which is undefined. Change to this:
success: function(response) {
Updating with an array of objects of type
   id: '',
   value: ''
Use for loop to iterate the response (array) and build the new list of elements:
function updateGEGsList(updated_gegs)
  var items = [];
  for (var i in updated_gegs) {
      var item = updated_gegs[i];
      items.push('<li id="' + + '">' + item.value + '</li>');

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.