Hi I had just started to use Ajax and am getting an input from a textfield (id_title) in html to retrieve information from the database dynamically. It is now working fine when there is input in the textfield from the user, however when there is no input, the database still retrieves the first few records in the database. How can I prevent calling the success function when 'id_title' is empty?
Edit:
Perhaps I should add that I'm using Ajax together with the Django framework. When there is no input the first 10 records are retrieved. I'm not sure how to stop sending records to 'qna/rec_results.html' when there is no input received from 'query' at the django function.
Django Function (Referred function at /qna/question_t_lookup/)
def question_autocomplete_lookup(request):
results = []
model_results = Tags.objects.filter(name__icontains = q)
if request.method == "GET":
if request.GET.has_key(u'query') :
value = request.GET[u'query']
model_results = Question.objects.filter(title__icontains = value)
else :
model_results = Question.objects.all()
else :
model_results = Question.objects.all()
paginator = Paginator(model_results, 10)
new_rec_list = paginator.page(1)
return render_to_response('qna/rec_results.html',{'rec_list' : new_rec_list})
AJax Function
function load_qn_search() {
$.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!");
}
}
});
};
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!");
}
}
});
};
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.
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 = []
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 = []