0

I searched for term "bi" which should return a username with initial "bi..." but nothing is displayed, No dropdown Here are my codes.

search.html

<html>
<div class="ui-widget">
  <label for="search4">search4: </label>
  <input id="search4">
</div>

<script type="text/javascript">
$(function(){
  $("#search4").autocomplete({
    source: '/rating/searchresult/',
    minLength: 2,
  });
});
</script>
</html>

url.py

url(r'^searchresult/', 'rating.views.search_images'),

views.py

def search_images(request):
    if request.is_ajax():
        s = request.GET.get("term", '')
        search_result = UploadImage.objects.filter(user__username__icontains = s )[:20]
        search = []
        for result in search_result:
            json_d = {}
            json_d['id'] = result.id
            json_d['name'] = result
            json_d['value'] = result
            search.append(json_d)
        data = m_json.dumps(search)
    else:
        data = 'error'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

if I search a value Ajax doesnot respond and returned nothing in dropdown, while the term is passed in URl

[04/Aug/2016 08:48:46] "GET /rating/searchresult/?term=bi HTTP/1.1" 200 2661

I can't understand where is the problem Ajax or Django Also my content type is text html see here

1 Answers1

0

Okay so technically you are doing it all wrong.

The source attribute of autocomplete requires an array of strings or data that you want to provide the user as autocomplete options in an input field.

Now what you are trying to do is to simply give the url corresponding to a particular view class or method in your views.py in your source of autocomplete, when actually what you need to do was to get an ajax response by hitting that url and then you'll get the required response from that class/method corresponding to that url.

Now you'll feed this response to the source of autocomplete

See here how the source of autocomplete works -> http://api.jqueryui.com/autocomplete/#option-source

And the official documentation of ajax -> http://api.jquery.com/jquery.ajax/

Documentation of $.get() -> https://api.jquery.com/jquery.get/

So your javascript file will look like this:

$(document).on('ready', function(){
      populateSearchFieldList();
      // all other code according to your needs

});   

function populateSearchFieldList() {

    var url = "/rating/searchresult/";
    $.get(url, function(response) {

            // console.log("Success..!!");
            console.log(response);

           // now in views.py, you've returned a list in which every 
           // object has an id, name and value but you
           // want only the names in your autocomplete. So for that, first
           // you'll have to create a list of just the names and then feed
           // that list to the source of autocomplete. Like this

           var searchFieldOptions = [];
           var i = 0;

           $.each(response,function(){
                searchFieldOptions.push(response[i].name);
                i++;
           });

           // and now make the source of autocomplete as 
           // searchFieldOptions like this

           $(function(){
                $("#search4").autocomplete({
                    source: searchFieldOptions,
                    minLength: 2,
                });
            });               

       });
}

Now if it worked successfully, then you'll have the required data in the response you received in the success function. Now you can use this response as the source of autocomplete if its simply a list or can further modify this response and form an array of desired contents as per your requirements.

Ankush Raghuvanshi
  • 1,392
  • 11
  • 17
  • thnks for replying, but where to put the autocomplete function. in your code, sorry i dont know JS, i juz followed the given blog – Sajna Abubacker Aug 05 '16 at 08:15
  • I'll edit my answer to show you where you can put the `autocomplete` function. – Ankush Raghuvanshi Aug 05 '16 at 08:20
  • Sorry but i can't understand what to pass in data, I tried your script, but it doesnt work – Sajna Abubacker Aug 05 '16 at 08:47
  • nothing is shown on console, also the term is not passed, but my friend did the same thing from the blog and it worked – Sajna Abubacker Aug 05 '16 at 08:51
  • I also got an error Uncaught SyntaxError: Unexpected token ; – Sajna Abubacker Aug 05 '16 at 09:10
  • Okay so basically, there are two ways to get the info from your `views.py` which you need to display in an `input` field of a form. Either you use Ajax call (when you are submitting some form data, and in response to that your `views` return some data, which you use in your autocomplete) or you can simple make a `GET` call as well when you don't have any to data to submit but all you want is to get the data from your views which will be used in your autocomplete. So do you have any data to submit and then get the response accordingly or you simply need some data from views, nothing to submit? – Ankush Raghuvanshi Aug 05 '16 at 09:17
  • I just want to get the username from model, when i type b.. which should show username with initial b – Sajna Abubacker Aug 05 '16 at 09:27
  • In that case, you don't really need an `ajax` call. I `get` call will be more suitable. Let me edit my answer accordingly. – Ankush Raghuvanshi Aug 05 '16 at 09:36
  • but how can it return the username as i m typing, doesnt it require ajax – Sajna Abubacker Aug 05 '16 at 09:43
  • Yea `ajax` is required. $.get() is just a shorthand for $.ajax() but abstracts some of the configurations away. I'll edit my answer, and that will make things a lot clear for you. :) – Ankush Raghuvanshi Aug 05 '16 at 10:04
  • See this for a better understanding -> http://stackoverflow.com/questions/3870086/difference-between-ajax-and-get-and-load – Ankush Raghuvanshi Aug 05 '16 at 10:06
  • sorry for late reply, i tried ur code, now the term is not even passed into the URL – Sajna Abubacker Aug 08 '16 at 09:14
  • Where exactly is that `term` in your HTML?? I mean what data do you want to send from your frontend i.e., html to backend, which you are calling as `term`? Coz I see you are trying to access something known as `term` in your views in `GET`, but where is this `term` in your html?? It has to be somewhere in your html? – Ankush Raghuvanshi Aug 08 '16 at 19:03