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

luftikus

New Member
#1
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...

HTML:
Mã:
<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>
    ....
   </ul>
 </div>
JS:
Mã:
// 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:
Mã:
// get data
$("#query2").keyup(
    function()
    {
        $.ajax({
            type: 'POST',
            url: 'etc/php/autocomplete_mea.php',
            data: 'term=' + $("#query2").val(),
            dataType: "json",
            success: function(response) {
                updateGEGsList(data);

            }       
        })
    }
)
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.
Mã:
[{"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!
 

Admin

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