2

I am working in asp.net MVC. I need a text box to autocomplete by ajax function. Ajax function can't call values from the controller.

Here is the code:

 $( "#birds" ).autocomplete({
      source: function( request, response ) {
        $.ajax( {
          url: "search.php",
          dataType: "jsonp",
          data: {
            term: request.term
          },
          success: function( data ) {
            response( data );
          }
        } );
      },
      minLength: 2,
      select: function( event, ui ) {
        log( "Selected: " + ui.item.value + " aka " + ui.item.id );
      }
} );
2
  • Plase, post your code Commented Jan 21, 2020 at 8:38
  • Ajax functions CAN get values from controllers Commented Jan 21, 2020 at 9:02

1 Answer 1

2

Here is the complete code:

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $( function() {
            var cache = {};
            $( "#birds" ).autocomplete({
                minLength: 2,
                source: function( request, response ) {
                    var term = request.term;
                    if ( term in cache ) {
                        response( cache[ term ] );
                        return;
                    }

                    $.getJSON( "Your Controller URL", request, function( data, status, xhr ) {
                        cache[ term ] = data;
                        response( data );
                    });
                }
            });
        } );
    </script>

Your Controller should response the data in JSON format like:

[{"id":"Locustella naevia","label":"Common Grasshopper Warbler","value":"Common Grasshopper Warbler"},{"id":"Locustella certhiola","label":"Pallas`s Grasshopper Warbler","value":"Pallas`s Grasshopper Warbler"}]

Your JSON should be dynamic, otherwise, it will respond you the same JSON. You should filter your data in your controller before responding back to the AJAX and the data always in the JSON format.

You can find more about autocomplete on https://jqueryui.com/autocomplete/ & https://jqueryui.com/autocomplete/#remote-with-cache

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.