lulu
lulu

Reputation: 271

Django: Ajax search stopped working

I don't know jquery or javascript really, but I've been following this tutorial: http://www.youtube.com/watch?v=jKSNciGr8kY

It has been working perfectly fine, until at some point, it just stopped working. Now what it does is that whatever I type in into the input field it returns all the Informations in the database. It is supposed to return "None to show!" when the search_text does not correspond to Information in the database, but it still returns all the entries.

Here's the view for it:

def search_infos(request):
    if request.method == 'POST':    
        search_text = request.POST['search_text']
    else:
        search_text = ''
    u = request.user
    custom_user = CustomUser.objects.get(user=u)
    infos = Info.objects.filter(organization_name__contains = search_text, game__in=custom_user.game.all(), department__in = custom_user.department.all()).distinct()
    return render_to_response('logins/ajax_search.html', {'infos' : infos})

Here's the template for ajax_search:

{% if infos.count > 0 %}

    {% for info in infos %}
        <li><a href="{{ info.id }}/">{{ info.organization_name }}</a></li>
    {% endfor %}

{% else %}

    <li>None to show!</li>

{% endif %}

Here is the ajax file itself:

$(function(){

    $('#search').keyup(function() {

        $.ajax({
            type: "POST",
            url: "/logins/search/",
            data: { 
                'search_text' : $('#search').val(),
                'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });

    });

});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
}

And I also have included this

<script src="{% static "assets/js/jquery-2.0.0.min.js" %}"></script>
    <script src="{% static "assets/js/ajax.js" %}"></script>

in my base.html file and this:

<div id = "search">
    <h3>Search</h3>
    {% csrf_token %}
    <input type="text" id="search" name="search" />
    <ul id="search-results">
    </ul>
</div>

in the template which I want to have the search box in.

What am I doing wrong?

Thanks in advance!

Here are the models:

from django.db import models
from django.contrib.auth.models import User, UserManager


class Department(models.Model):
    name = models.CharField(max_length=200)
    def __unicode__(self):  
        return self.name

class Game(models.Model):
    name_of_the_game = models.CharField(max_length=200)
    def __unicode__(self):  
        return self.name_of_the_game

class Info(models.Model):
    organization_name = models.CharField(max_length=200)
    url = models.URLField(max_length = 200, blank = True)
    user_name = models.CharField(max_length=200, blank = True)
    password = models.CharField(max_length=200, blank = True)
    comments = models.TextField(max_length = 500, blank = True)
    game = models.ManyToManyField(Game, blank = True)
    department = models.ManyToManyField(Department, blank = True)
    def __unicode__(self):
         return self.organization_name+ ': '+ 'user name: ' +self.user_name+ ', '+ 'password: ' + self.password


class CustomUser(models.Model):
    department = models.ManyToManyField(Department)
    game = models.ManyToManyField(Game)
    user = models.OneToOneField(User)

Upvotes: 0

Views: 244

Answers (2)

yuvi
yuvi

Reputation: 18427

The problem is with your html, you have two dom elements named 'search':

<div id = "search"> #here
    <h3>Search</h3>
    {% csrf_token %}
    <input type="text" id="search" name="search" />  #and here
    <ul id="search-results">
    </ul>
</div>

So when you do

$('#search').val()

it's fetching the first object with an id of 'search', which isn't your text input but your entire div, and so the value is always an empty string.

On the server side you had another problem, where you allowed empty string to fetch all data, using @RaydelMiranda answer for this will solve it.

p.s

Using POST is meant to be used to add or alter data in your database. For simple fetching, it's better to use GET (and then you don't need csrf either). I'm not sure what's this tutorial is teaching you, but perhaps you should learn django and ajax seperatly from each other (I recommend nettut's jQuery in 30 days, done wonder for me)

Upvotes: 2

Raydel Miranda
Raydel Miranda

Reputation: 14360

I think your problem is in the view. Check this two lines:

search_text = ''

and

infos = Info.objects.filter(organization__name__contains = search_text, game__in=custom_user.game.all(), department__in = custom_user.department.all()).distinct()

search_text is an empty string, maybe

organization_name__contains = search_text

gets always true because '' is always contained inside any string.

Try this:

def search_infos(request):
    infos = []
    if request.method == 'POST':    
        search_text = request.POST['search_text']
        u = request.user
        custom_user = CustomUser.objects.get(user=u)
        infos = Info.objects.filter(organization_name__contains = search_text, game__in=custom_user.game.all(), department__in = custom_user.department.all()).distinct()
    return render_to_response('logins/ajax_search.html', {'infos' : infos})

Upvotes: 2

Related Questions