views:

149

answers:

1

I'm building a very simple page that is a to-do list. It accepts input from a user via a form for new to-dos, POSTs the to-do to the server, then receives (almost) the same data back and adds it to a list. However, every time data is supposed to be sent to the server, the $.ajax function is called twice.

My js:

// todo.js
function onload() {
 $( "#datepicker" ).datepicker();
 $( "#todoform" ).submit(function(e){
  e.preventDefault();
  sendtodo();
  return false;
 });
}
function sendtodo() {
 $.ajax({
  url: '/blog/todo/newtodo/',
  type: "POST",
  success: function(data) {
   receivetodo(data);
  },
  data: ({
   body: $('#newbodytextarea').val(),
   title: $('#titleinput').val(),
   dateDue: $('#datepicker').val(),
   time: $('#timepicker').val(),
   category: $('#newcategory').val()}),
});
}
function receivetodo(data) {
 $('#todobody').append(data);
}

And part of my HTML:

<html>
<head>
<title>Todo list</title>
<link href="/django_media/css/todo/todo.style.css" rel="stylesheet" type="text/css">
<link href="/django_media/css/jquery-ui-1.8.5.custom.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/django_media/js/jquery.js"></script>
<script type="text/javascript" src="/django_media/js/jquery-ui-custom.js"></script>
<script type="text/javascript" src="/django_media/js/todo/todo.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
  onload();
 });
</script>
</head>
<body>
[.................]
</body>
</html>

In case it matters, I am using Django for my back-end. The data that is being returned is a <div> containing a couple other <div> tags and some <h1> and <p> tags. The part of the code that appends the received HTML to the page works fine except that it appends it twice (and the data really is in the database twice).

I've tried using $("#todoform").click(function(e){ instead of $("#todoform").submit(function(e){ but that didn't change anything. I also made sure onload() is only being called once. Why is sendtodo() executing twice?

If you need any other code I can post it as well.

+1  A: 

Probably onload() is being called twice, check all occurrences of it through your code. If you call .submit() twice, the onsubmit event is appended with the code given, not replaced.

To debug, put an alert('anything') inside sendtodo() and check if it's really being called twice when submitting.

You can also do:

$('#todoform').removeAttr('onsubmit').submit( ...

But it would be better to find out why it's being bound twice

bortao
`sendtodo()` is being called twice when I submit the form. Firebug is showing the same listener is bound to my form twice.
puddingfox