Friday, 30 August 2013

Django, jquery and $.get

Django, jquery and $.get

Is there a django function to detect if an ajax query was sent with $.get?
Let me explain...
I use Ajax for 2 things:
1/ from my menu I display the content of each page with $.get (already
implemented, it worked well until I started developing the second point)
2/ inside a form, when I click on a button, I use $.ajax to display a
success or error message (currently being developed)
At the end of the first point, my view is unchanged. The last line:
return render_to_response('auth/index.html', response_dic,
context_instance=RequestContext(request))
However I had to change it for the second point:
if request.is_ajax():
#transform the data to json so it can be used in jquery
return HttpResponse(simplejson.dumps(response_dic),
mimetype='application/json')
#normal post with reload
else:
return render_to_response('auth/index.html', response_dic,
context_instance=RequestContext(request))
But now nothing is displayed anymore when I click on a link of my menu! I
think I know why: I call my view with $.get. In my view, request.is_ajax()
returns True so it doesn't render the view as it should (it returns
HttpResponse instead of render_to_response)!
So I repeat my question: is there a function to detect if ajax was used
with a GET? If it's not clear, ask me more details! Here is my jQuery
function:
//load the content of the page (right side) with Ajax (no need to reload
the menu and header)
function load_content(link)
{
$.get(link, function(data)
{
var title=$(data).find("#title");
var content=$(data).find("#content");
$("#title_base").html(title);
$("#content_base").html(content);
});
//change the active link in the menu
$('.active').removeClass('active');
//~ $(this).addClass("active");
$('#menu a[href*="' + link.split("/")[2] +
'"][class!="noselect"]').parent().addClass('active');
}
Idea: Should I use two different views?

No comments:

Post a Comment