title: Ajax Django Login/Authentication without re-direct
body: <p>I am trying to have an authentication set-up similar to that of StackOverflow, where the normal browsing is never affected unless there are some privileged actions which requires authentication (Do not bother users until then).</p>
  
  <p>It should be as "Log In" if not logged in or "UserName" if logged in. </p>
  
  <p>The relevant part of base.html (from fallr.net) (extended by index.html) looks like :</p>
  
  <pre><code>            &lt;script type="text/javascript"&gt;
              //&lt;![CDATA[
  
              $(document).ready(function(){
  
              var methods = {
  
              forms : function(){
              var login = function(){
              var user = $(this).children('form').children('input[type="text"]').val();
              var pass = $(this).children('form').children('input[type="password"]').val();
              var dataString = '&amp;username=' + $('input[name=username]').val() + '&amp;password=' + $('input[name=password]').val();
              if(user.length &lt; 1 || pass.length &lt; 1){
              alert('Invalid!\nPlease fill all required forms');
              } else {
              alert('username: '+user+'\npassword: '+pass);
              $.ajax({
              type: "POST",
              url: "/login",
              dataType: "html",
              data: {
              username : user,
              password : pass,
              csrfmiddlewaretoken : '{{ csrf_token }}'
              },
              success: function(json){alert (json.server_response);},
              error: function(xhr,errmsg,err) { alert(xhr.status + ": " + xhr.responseText); }
              });
              $.fallr('hide');
              return false;
              }
              }
  
              $.fallr('show', {
              icon        : 'secure',
              width       : '320px',
              content     : '&lt;h4&gt;Sign in&lt;/h4&gt;'
              + '&lt;form&gt;'
              +     '&lt;input name="username" placeholder="username" type="text"/'+'&gt;'
              +     '&lt;input name="password" placeholder="password" type="password"/'+'&gt;'
              + '&lt;/form&gt;',
              buttons : {
              button1 : {text: 'Submit', onclick: login},
              button4 : {text: 'Cancel'}
              }
              });
              }
              };
  
              //button trigger
              $('a[href^="#fallr-"]').click(function(){
              var id = $(this).attr('href').substring(7);
              methods[id].apply(this,[this]);
              return false;
              });
  
              // syntax highlighter
              hljs.tabReplace = '    ';
              hljs.initHighlightingOnLoad();
              });
  
              //]]&gt;
              &lt;/script&gt;
  </code></pre>
  
  <p>The urls.py looks like :</p>
  
  <pre><code>            from django.conf.urls import patterns, include, url
              #from triplanner.views import *
  
  
              # Uncomment the next two lines to enable the admin:
              # from django.contrib import admin
              # admin.autodiscover()
  
              urlpatterns = patterns('',
              url(r'^$', main_page),
              url(r'^login$',ajax_login),                 
              url(r'^login/$','django.contrib.auth.views.login'),
              url(r'^logout/$', logout_page),
  
              # our application page
              url(r'^account/',include('tripapp.urls')),              
              )
  </code></pre>
  
  <p>Also, '^login/$' is the previous implementation for learning which I want to replace with Ajax login.</p>
  
  <p>And my views.py:</p>
  
  <pre><code>            # -*- coding: utf-8 -*-
              from django.contrib.auth import logout
              from django.http import HttpResponseRedirect
              from django.shortcuts import render_to_response
              from django.contrib.auth import authenticate, login
              #from django.http import HttpResponse
              from django.template import RequestContext
              #from django.utils import simplejson
  
  
  
              def main_page(request):
              return render_to_response('index.html', context_instance=RequestContext(request))
  
  
              def logout_page(request):
              """
              Log users out and redirect them to the main page
              """
              logout(request)
              return HttpResponseRedirect('/')
  
  
              def ajax_login(request):
              """  
              This view logs a user in using the POST data.
              """
  
              if request.method == 'POST':
              print request.POST['username']
              username = request.POST['username']
              password = request.POST['password']
              print username
              print password
              user = authenticate(username=username, password=password)
              if (not user is None) and (user.is_active):
              login(request, user)
              response_dict = {}
              response_dict.update({'server_response': username})
              #return HttpResponse(simplejson.dumps(response_dict),mimetype='applicaion/javascript')
              return render_to_response('index.html',{'username' : user}, context_instance=RequestContext(request))
              # Set Session Expiry to 0 if user clicks "Remember Me"
              #if not request.POST.get('rem', None):
              #   request.session.set_expiry(0)
              #data = username
              else:
              return render_to_response('index.html', context_instance=RequestContext(request))
  </code></pre>
  
  <p>I am getting a 403 Error like "[20/Aug/2013 00:29:20] "POST / HTTP/1.1" 403 2294"</p>
  
  <p><strong>UPDATE NUMBER 1</strong>:</p>
  
  <p>With the changed urls.py, views.py and javascript I am able to get a 200 response, but it gives alert window saying undefined and alerting me "Prevent this page from creatng dialog boxes"</p>