[Answered ]-Calling function from jQuery with Django not working correctly

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)
    });
});

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

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"
});

Leave a comment