Friday, December 27, 2013

Re: Displaying HTML forms through AJAX

Arun,

Do yourself some favors.

1. use jQuery for Ajax (or some other lib). You are doing it the very hard and not cross-browser compatible way.
2. use Django's template system for HTML generation.
3. if you do number 2 you can embed the CSRF token in the template render like you are supposed to.

-Aaron



On Thursday, December 26, 2013 1:10:42 PM UTC-5, Arun Kaushik wrote:
I am a newbie. I am learning Django by developing a web application. There is use-case where I got stuck. 
there are 3 buttons on a html page
Personal info
Education
Work Experience
It is desired when the user click any of the button, respective html form shall be displayed on right-half of web-page.

What I have tried is this, onclick function of buttons:
    function myfun()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("rightpan").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","{% url "polls:demo_test" %}",true);
xmlhttp.send();
}
</script>

in views.py, demo test does this:

def demo_test(request):
return HttpResponse("<form name='reg' onsubmit='return ValidateForm(this)' action='{% url 'polls:signupexec' %}'  method='post'><tr><td><div>Firstname:</div></td><td><input type='text' name='first_name' /></td></tr><tr><td><div>Lastname:</div></td><td><input type='text' name='last_name' /></td></tr><tr><td><input name='submit' type='submit' value='Submit' /></td></tr></form>")

  1. First of all, it works fine except that it does not embed CSRF_TOKEN in the form, which is important.
  2. Secondly, I feel that this approach is against the philosophy of django.
Please give some suggestions on how can I do this. Loading HTML Forms dynamically through AJAX.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4693cb5a-5c2f-43db-94df-c56988378b6d%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment