0

I am trying to use the jQuery plugin "autocomplete" with custom data. It does not work in my code.

The ajax call works fine, I see the response. But the answer is not displayed on the page.

The response is something like following :

[{"id_pseudo":12,"nom":"COLLINS","prenom":"Phil","image":"images\/avatar_48x48.png"}]

My js code is :

$('#rechercher_ami').autocomplete({
    source : function(requete, reponse){
        $.ajax({
            url : $('#url_for_ajax').val() + '/getRechercherAmiAjax',
            dataType : 'json', 
            data : {ami : $('#rechercher_ami').val(), maxRows : 15},
            beforeSend : function() {$('#waiting_autocomplete').show();}, 
            success : function(donnee){

                $('#waiting_autocomplete').hide();

            }
        });
    },
    minLength: 3,
    delay:500,

    select: function( event, ui ) {
        alert('hello');
         return false;
      }
})

 $('#rechercher_ami').data( "ui-autocomplete" )._renderItem = function( ul, item ) {
    return $( "<li>" )
    .append( "<a>" + item.nom + "<br>" + item.prenom + "</a>" )
    .appendTo( ul );
}; 

What's wrong on this code?

1 Answer 1

1

You should call the response callback and pass the result in an accepted format mentioned in the documentation.

For example:

$('#rechercher_ami').autocomplete({
  source: function(request, response) {
    $.ajax({
      url: $('#url_for_ajax').val() + '/getRechercherAmiAjax',
      dataType: 'json',
      data: {
        ami: request.term,
        maxRows: 15
      },
      beforeSend: function() {
        $('#waiting_autocomplete').show();
      },
      success: function(data) {
        $('#waiting_autocomplete').hide();
        var result = $.map(data,function(item){ // form the data as you wish
          return {
                  label:item.nom,
                  value:item.id_pseudo
                 };
          });
        response(result); // must pass valid data to response call back
      }
    });
  },
  minLength: 3,
  delay: 500,

  select: function(event, ui) {
    alert('hello');
    return false;
  }
});
Sign up to request clarification or add additional context in comments.

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.