How to make ajax call and return results when entering text input

I want to implement some functions that occur when entering some text in

<input path="tags" id="input-search"/>

a list of suggested tags should appear , like Tages

after calling ajax. I have a database query

public interface TagRepository extends JpaRepository<Tag, Integer> {    
    @Query("SELECT t FROM Tag t WHERE name LIKE CONCAT('%', :name, '%')")
    List<Tag> findTagByName(@Param("name") String name);    
}

and controller code

@RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json")
    public  @ResponseBody List<Tag> getTags(@RequestBody Tag tag, HttpServletResponse response) {
        System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size()));
        return tagService.findTagByName(tag.getName());

    }

javascript for ajax -

 $(document).ready(function() {   
        $("#tag-search").autocomplete({
            source: function(request, response) {
                $.ajax({
                 url: "/app/getTags/", 
                 type: "POST", 
                 data: JSON.stringify({tag : request.term}),
                 dataType: "json",
                success: function(data) {
                    response($.map(data, function(v,i){
                        console.log();
                        return {
                            label: v.empName,
                            value: v.empName
                         };
                    }));
                }
               });              
            }   
        });
    });

<div class="col-md-10 col-md-push-1">                                                   
    <label class="floating-label" for="login-username">Tags</label>
    <form:input path="tags" cssClass="form-control" id="tag-search"/>
</div>

when I launch the application, I see this javaScript error in Developers Tools Snapshot

Attention!

I use Daemonite / material for my front-end and jQuery-Autocomplete , finally it’s good that the latest version of the application on GitHub can someone tell me how I can get rid of this error, any answer is welcome.

+4
9

, jQuery.

:

<script>
if (window.jQuery) {  
    alert('jQuery is loaded');
} else {
    alert('jQuery is not loaded');
}
</script>
+2

select2 jquery plugin. , . - http://select2.imtqy.com/select2/#infinite

:

enter image description here

:

$("#e7").select2({
    placeholder: "Search for a repository",
    minimumInputLength: 3,
    ajax: {
        url: "https://api.github.com/search/repositories",
        dataType: 'json',
        quietMillis: 250,
        data: function (term, page) { // page is the one-based page number tracked by Select2
            return {
                q: term, //search term
                page: page // page number
            };
        },
        results: function (data, page) {
            var more = (page * 30) < data.total_count; // whether or not there are more results available

            // notice we return the value of more so Select2 knows if more results can be loaded
            return { results: data.items, more: more };
        }
    },
    formatResult: repoFormatResult, // omitted for brevity, see the source of this page
    formatSelection: repoFormatSelection, // omitted for brevity, see the source of this page
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});

, , , , .

:

function repoFormatResult(repo) {
  var markup = '<div class="row-fluid">' +
     '<div class="span2"><img src="' + repo.owner.avatar_url + '" /></div>' +
     '<div class="span10">' +
        '<div class="row-fluid">' +
           '<div class="span6">' + repo.full_name + '</div>' +
           '<div class="span3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
           '<div class="span3"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
        '</div>';

  if (repo.description) {
     markup += '<div>' + repo.description + '</div>';
  }

  markup += '</div></div>';

  return markup;
}

function repoFormatSelection(repo) {
    return repo.full_name;
}

:

, , . typeahead.js, JavaScript . .

+2

, HTML JSON .

" <" . Chrome "" , - , .

+1

jquery.js. , .

0

, ;

json Java jquery. Java Ajax, Uncaught: .

     public static String toJSON(Object object) 
      { 
          if ( object == null ){
          return "{}"; 
          } 
          try { 
             ObjectMapper mapper = new ObjectMapper(); 
             return mapper.writeValueAsString(object); 
             } 
          catch (Exception e) { 
           e.printStackTrace(); 
          } 
        return "{}"; 
        } 

3 jackson-core-2.2.3.jar, jackson-annotations-2.2.3.jar jackson-databind-2.2.3.jar.

:

@RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json")
    public  @ResponseBody String getTags(@RequestBody Tag tag, HttpServletResponse response) {
        System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size()));
        return toJSON(tagService.findTagByName(tag.getName()));

    }
$(document).ready(function() { 
        var autoCompleteResult = '';  
        $("#tag-search").autocomplete({
            source: function(request, response) {
                $.ajax({
                 url: "/app/getTags/", 
                 type: "POST", 
                 data: JSON.stringify({tag : request.term}),
                 dataType: "json",
                success: function(data) {
                    autoCompleteResult = jQuery.parseJSON(data);
                    response($.map(autoCompleteResult, function(v,i){
                        console.log();
                        return {
                            label: v.empName,
                            value: v.empName
                         };
                    }));
                }
               });              
            }   
        });
    });

, .

0

, 500 internal server error, dataType: "json", ajax, json.

@RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json")
public  @ResponseBody List<Tag> getTags(@RequestBody Tag tag, HttpServletResponse response) {
    System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size()));
    return tagService.findTagByName(tag.getName());

}

: produces = "application/json" , json : return tagService.findTagByName(tag.getName()); json.

0

ajax

     contentType: 'application/json; charset=utf-8',

, ,

ajax, json-

dataType: 'json', Json Parsing Error

0

JavaScript

$(document).ready(function() {   
    $("#tag-search").autocomplete({
        source: function(request, response) {
            $.ajax({
             contentType: 'application/json; charset=utf-8',
             url: "/app/getTags/", 
             type: "POST", 
             data: JSON.stringify({'tag' : "'"+request.term+"'"}),
             dataType: "json",
             success: function(data) {
                response($.map(data, function(v,i){
                    console.log();
                    return {
                        label: v.empName,
                        value: v.empName
                     };
                }));
            }
           });              
        }   
    });
});
0

Source: https://habr.com/ru/post/1609553/


All Articles