1

Im trying to make a page that searched for users based on a users criteria. It then loads the results via AJAX response into a different DIV:

function search_friends() {
    $("#search-results").show();
    $("#loading1").show();
    var q = $("#id_q").val();
    var type = $("#id_search_type").val();
    $("#loading1").hide();
    $("#results").load("/search/friends/?ajax&q="+encodeURIComponent(q)+"&search_ty­pe="+encodeURIComponent(type));
    return false;
}

Inside this new results DIV, I have links for each user to be able to add them as a friend. Each link in this results DIV has a ID of each users userID and a class of user_link. When the logged in user clicks on the link I want it to pop up a confirmation box then send the request via AJAX. However, I cannot get the links to submit via AJAX like I want. The code I have is below:

{% for u in users %}
<div id="results">
    <img src="{{ u.profile_pic }}" class="xsmall-pic" /> <a href="/{{ u.username }}/">{{ u.username }}</a><br />
    <span class="small-date">{{ u.get_full_name }}</span>
    <span class="floatR" id="user_{{ u.id }}_link"><a href="#" id="{{ u.id }}" class="user_link">Add as friend</a></span>
</div>{% endfor %}

<script type="text/javascript" language="javscript">
    $(document).ready(function() {
        var csrf_token = "{{ csrf_token }}";
        $(".user_link").bind('click',function() {
            request_friend($(this).id,csrf_token)
        });
        $("#search-friends-form").submit(search_friends);

    });
</script>

In an external JavaScript file I have the following:

function confirm_request()

    return confirm("Are you sure you want to request this user as a friend?");
}

function request_friend(id,token)
    if (confirm_request())
    {
        var data1 = {to_friend: id,csrfmiddlewaretoken: token};
        $.post('/users/requests/friends/'+id+'/?ajax', 
                data1, function(json) {
                    $("#user_"+id+"_link").html(json.status);
                }, "json");
                return false;
    }
    else
    {
        return;
    }
}

Thanks for any help as Im not all that great with Javascript.

EDIT Python function called via AJAX

def search_for_friends(request):
users = False
friends = False
return_page = 'users/friend_search.html'
ajax = 'ajax' in request.GET
try:
    if 'q' in request.GET:
        form = FriendSearchForm(request.GET)
        if form.is_valid():
            if form.cleaned_data['search_type'] == 'username':
                users = CustomUser.objects.exclude(pk=request.user.id).filter(username__icontains=form.cleaned_data['q'])
            elif form.cleaned_data['search_type'] == 'name':
                users = CustomUser.objects.filter(Q(first_name__icontains=form.cleaned_data['q']) | Q(last_name__icontains=form.cleaned_data['q']))
            elif form.cleaned_data['search_type'] == "email":
                users = CustomUser.objects.filter(email__icontains=form.cleaned_data['q'])
            else:
                pass
        else:
            pass
    else:
        form = FriendSearchForm()
    if users != False:
        users = users
        error = False
    if users == "":
        users = ""
        error = "No users match the search term provided"
    if ajax:
        show_results = True
        context = RequestContext(request,{'users':users,'form':form,'show_results':show_results})
        return render_to_response('users/friend_search_results.html',context_instance=context)
    context = RequestContext(request,{'users':users,'form':form,'error':error})
    return render_to_response(return_page,context_instance=context)
except:
    form = FriendSearchForm()
    context = RequestContext(request,{'form':form})
    return render_to_response(return_page,context_instance=context)
vt-cwalker
  • 795
  • 2
  • 16
  • 34
  • You should fix your formatting, and then describe what isn't working. – Jack M. Apr 27 '11 at 21:50
  • If your referring to the formatting of how its in the post, I did the best I could. Its a lot better than it was to begin with.. As far as what isnt working, when clicking on each link in the results DIV, it doesnt do anything at all. It should call the request_friends function as is in the $(".user_link").bind() function – vt-cwalker Apr 27 '11 at 21:54
  • Is it making a request to the server? Is the request succeeding? Is the output simply not what you were expecting? We need details of how it isn't working. – Jack M. Apr 27 '11 at 21:57
  • No it isnt doing anything at all. I use firbug in Firefox and it doesnt show anything happening when I click any of the links in the AJAX loaded portion. – vt-cwalker Apr 27 '11 at 22:02
  • Is it throwing an error on load? Neither of your functions seem to have opening squigly brackets, which should throw errors. Are you being taken to the '#' anchor when you click the .user_link ? – Jack M. Apr 27 '11 at 22:09
  • Well I took out the beginning curly braces to get all the code within the code block on the page. But yes when I click on the links, it appends # to the end of the link – vt-cwalker Apr 27 '11 at 22:12
  • Can you post the ajax call which loads this into the page itself? – Jack M. Apr 27 '11 at 22:13
  • Yea I just realized that I shouldve just edited the post to put in the AJAX call but you beat me to it as I was trying to do it. LOL – vt-cwalker Apr 27 '11 at 22:21

3 Answers3

1

If you want to keep from having the JavaScript in the AJAX response, you could have the completion event of .load() take the responsibility of setting up the click events:

var url = "/search/friends/?ajax&q="+encodeURIComponent(q)+"&search_ty­pe="+encodeURIComponent(type);
$("#results").load(url, function() {
    var csrf_token = "{{ csrf_token }}";
    $(".user_link").bind('click',function() {
        request_friend($(this).id,csrf_token)
    });
});
Jack M.
  • 30,350
  • 7
  • 55
  • 67
1

if I understand your question correctly, you want to make sure click handlers work for links loaded through a later AJAX call?

In jQuery, use the $('.user_link').live('click', function() {}) handler once to assign a click event handler to all current and future links.

Max
  • 6,901
  • 7
  • 46
  • 61
0

The Javascript being returned from your AJAX call does not get evaluated unless you specifically tell jQuery to evaluate it. This is done by specifying the dataType on your AJAX calls, which .load() doesn't support.

As seen in this answer, you should use jQuery.get() or $.ajax and specify your data type:

$.ajax({
  type: "GET",
  url: "yourPage.htm",
  dataType: "html"
});
Community
  • 1
  • 1
Jack M.
  • 30,350
  • 7
  • 55
  • 67
  • The $.load function is working. Its the javascript function with the $.post method thats not doing anything. Its not even invoking the function request_friend – vt-cwalker Apr 27 '11 at 22:24
  • Add this to your javascript right below `$(document).ready(function() {`: `alert("I am being evaluated!");`. You will not see a pop up. that means the Javascript is not being evaluated after it is loaded through AJAX. – Jack M. Apr 27 '11 at 22:27
  • Well I know that when a portion is loaded via AJAX that the $(document).ready portion doesnt really do anything. What Im trying to figure out is how to allow those links to invoke a function via jQuery without having to put a onclick even handler to each link. – vt-cwalker Apr 27 '11 at 22:31