[Answer]-Ajax used in Django

1👍

Thanks to machaku, I was able to come out with this that caught the empty string issue! Thanks alot!

if len(value.strip()) > 0:
            model_results = Question.objects.filter(title__icontains = value)
        else:
            model_results = [] 

0👍

function load_qn_search() {
     $.ajax({
       type: "GET",
       url: '/qna/question_t_lookup/',
       data: {
            query: $("#id_title").val()},
       success: function(data) {
               if($("#id_title").val()=='') return false; // stop executing 
               $('#ajax_reload_content').html(data);
       },
       statusCode: {
         500: function() {
           alert("Opps! There is a error!");
         }
       }
     });
};

0👍

Try following:

function load_qn_search() {
    if($("#id_title").val())
    {
     $.ajax({
       type: "GET",
       url: '/qna/question_t_lookup/',
       data: {
            query: $("#id_title").val()},
       success: function(data) {              
               $('#ajax_reload_content').html(data);
       },
       statusCode: {
         500: function() {
           alert("Opps! There is a error!");
         }
       }
     });
    }
};

Make the ajax call only if the text value is not empty.

👤Shant

0👍

You are returning model_results = Question.objects.all() when query is not availabe. Try create empty model_results when query is empty.

Example:

if request.GET['query']:
    # return your query results
else:
    model_results = []        

Leave a comment