Basic AJAX usage in Django
Check out the new site at https://rkblog.dev.
14 July 2008
Comments
On dynamicdrive.com there is a simple Javascript library called ajaxroutine.js which we will use to make a simple AJAX powered registration form. First download the Javascript file and put it in the media folder. Then add it to the HTML template of the page:
<script type="text/javascript" src="/site_media/ajaxroutine.js"></script>
We will want to make a registration form that checks if the entered email or login is already taken. Here is a simple form:
<div id="aj" style="text-align:center;"></div>
<form action="." method="post" name="r">
<input type="text" id="id_login" name="login" size="20" value="{{ data.login }}" maxlength="200" />
<input type="text" id="id_email" name="email" size="20" value="{{ data.email }}" maxlength="75" />
<input type="submit" value="Register">
</form>
<script type="text/javascript">
function processGetPost()
{
var myajax=ajaxpack.ajaxobj
var myfiletype=ajaxpack.filetype
if (myajax.readyState == 4)
{
if (myajax.status==200 || window.location.href.indexOf("http")==-1)
{
// if we got something show it
if (myajax.responseText.length > 3)
{
document.getElementById('aj').innerHTML='<h1>' + myajax.responseText + '</h1>';
}
else
{
// clear the div
document.getElementById('aj').innerHTML='';
}
}
}
}
</script>
onblur="ajaxpack.getAjaxRequest('/VIEW/URL/', 'param=value', 'txt');"
/VIEW/URL/ is a page which will be called. Second argument is a GET arguments string, which can be used to send values from the form:
document.FORM_NAME.FIELD_NAME.value document.r.email.value
<div id="aj" style="text-align:center;"></div>
<form action="." method="post" name="r">
<input type="text" id="id_login" name="login" size="20" value="{{ data.login }}" maxlength="200" onblur="ajaxpack.getAjaxRequest('/user/checkreg/', 'login=' + document.r.login.value, processGetPost, 'txt');" />
<input type="text" id="id_email" name="email" size="20" value="{{ data.email }}" maxlength="75" onblur="ajaxpack.getAjaxRequest('/user/checkreg/', 'email=' + document.r.email.value, processGetPost, 'txt');" />
<input type="submit" value="Register">
</form>
def checkreg(request):
if request.GET.has_key('login'):
try:
User.objects.get(username=request.GET['login'])
except:
return HttpResponse('Login FREE')
else:
return HttpResponse('Login TAKEN')
if request.GET.has_key('email'):
try:
User.objects.get(email=request.GET['email'])
except:
return HttpResponse('Email FREE')
else:
return HttpResponse('Email TAKEN')
return HttpResponse('')
RkBlog
Check out the new site at https://rkblog.dev.
Comment article