title: Using AJAX to create an Object which then appears in dropdown box
body: <p>Hi I've run into a problem where I am trying to make it so when a button is clicked an object can be made. I can't get it to work as for some reason it will not validate, however if I change input type to submit it works fine. </p>
  
  <p>But the problem is when I use it as submit the page redirects which defeats the purpose of using AJAX.</p>
  
  <p>I can't seem to find a good tutorial for what I'd like to do, any help or links would really be appreciated!</p>
  
  <p><strong>Models</strong></p>
  
  <pre><code>class MemberRole(models.Model,get_fields):
      name = models.CharField(max_length = 20)
  </code></pre>
  
  <p><strong>Form</strong></p>
  
  <pre><code>class MemberRoleForm(forms.ModelForm):
      class Meta:
          model = MemberRole
  </code></pre>
  
  <p><strong>Views</strong>
  This view builds the form for the memberrole model</p>
  
  <pre><code>def add_member(request):
      model_url = 'member-add'
      rform = MemberRoleForm(instance=MemberRole())
      return render_to_response('create_model.html', {'role_form': rform,'model_url': model_url,},context_instance=RequestContext(request))
  </code></pre>
  
  <p>This ajax called view</p>
  
  <pre><code>@require_POST
  def ajax(request):
      data = request.POST.get("rolename","")
      if request.method == 'POST':
          rform = MemberRoleForm(request.POST, instance=MemberRole())
          if rform.is_valid():
              new_role = rform.save()
              new_role.name = data
              return HttpResponse("SuccessFully Saved")
          else:
              return HttpResponse("Error in saving")
  </code></pre>
  
  <p><strong>Template</strong></p>
  
  <pre><code>    &lt;div id="addRoleOnMemberForm"&gt;
          &lt;form id = "addrole" onsubmit= "return false;" method="POST"&gt;
          {% csrf_token %}
          {% for field in role_form %}
                  {{ field.errors }}
                  {{ field.label_tag }} {{ field }} //#id_name is in here
          {% endfor %}
          &lt;input id="addrolebutton" type="button" onclick = "createit()" value="Add New Role"/&gt;
      &lt;/div&gt;
      {% for x in role_list %}
  
      &lt;div&gt;
          &lt;p&gt; This shows a role was made &lt;/p&gt;
      &lt;/div&gt;
      {% endfor %}
  </code></pre>
  
  <p><strong>Script</strong></p>
  
  <pre><code>&lt;script&gt;
      function createit(){
      $.ajax({
      type: "POST",
      url:"ajax",
  dataType:"json",
  async: true,
  data: {
      csrfmiddlewaretoken: '{{ csrf_token }}',
  rolename: $('#id_name').val()
  },
  
  });
  }
  &lt;/script&gt;
  </code></pre>