views:

45

answers:

0

I have a bit of a problem.

I have ten forms in my app similar to facebooks commenting forms.

I have successfully managed to pass the form for processing by making use of jQuery's $.ajax function.

All of this works fine, but for some reason the app sends 10 post signals and then reloads ten times, causing the user to experience having to wait until all has finished loading.

The form

<form action="{% comment_form_target %}" method="post" class="comment-form">
  {% if next %}<input type="hidden" name="next" value="{{ next }}" />{% endif %}
  {% for field in form %}
    {% if field.is_hidden %}
      {{ field }}
    {% else %}
      {% if field.errors %}{{ field.errors }}{% endif %}
      <p
        {% if field.errors %} class="error"{% endif %}
        {% ifequal field.name "honeypot" %} style="display:none;"{% endifequal %}>

      </p>
    {% endif %}

  {% endfor %}
  <textarea id="id_comment" rows="1" cols="60" name="comment" class='id_comment'></textarea>
  <p class="submit">
    <input type="submit" name="post" class="submit-post blue comment_submit" value="{% trans "Comment" %}" id="button" style="float:right;margin-top:-6px;margin-bottom:4px;"/>
  </p>
  <div class="clearfix"></div>
</form>

the jQuery

$(document).ready(function(){
 ### this first bit goes through the django form and assigns a unique ID
    $('.comment-form').each(function(){
  var element = $(this).find('#id_object_pk').val();
  $(this).attr('id', element);
  $(this).find('#button').attr('id', element);
  $(this).find('#id_content_type').attr('id', 'id_content_type' + element);
  $(this).find('#id_timestamp').attr('id', 'id_timestamp' + element);
  $(this).find('#id_security_hash').attr('id', 'id_security_hash' + element);
  $(this).find('#id_comment').attr('id', 'id_comment' + element); 
 });

 ### this bit is where the magic happens
    $(".comment_submit").click(function(){
  var element = $(this);
  var ID = element.attr('id');

  var content_type = $('#id_content_type'+ID).val();
  var timestamp = $('#id_timestamp'+ID).val();
  var security_hash = $('#id_security_hash'+ID).val();
  var comment = $('#id_comment'+ID).val();
  var dataString = 'content_type='+ content_type +'&timestamp='+ timestamp +'&security_hash=' + security_hash + '&comment=' + comment + '&object_pk=' + ID;

  $('#id_comment'+ID).val('').addClass("greyout");

  $.ajax({
   type: "POST",
   url: "/comments/post/",
   data: dataString,
   success: function(){
    $.get('/wall/', { user:'{{ sent_user }}' }, function(data){
     $('#news').html(data);
    });
   }
  });
  return false;
 });

});

So when a user submits, it then sends 10 form submits, accepts the one with data but also reloads 10 times... Where am I going wrong with this