JQuery Ajax function called twice with the same data

I am creating a very simple page that is a to-do list. It accepts user input through a form for new to-dos, POST data executed on the server, then receives (almost) the same data and adds it to the list. However, each time data is 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 that matters, I use Django for my back-end. The returned data is <div>one containing a couple of other tags <div>and some <h1>and tags <p>. The part of the code that adds the received HTML to the page works fine, except that it adds it twice (and the data is actually in the database twice).

$("#todoform").click(function(e){ $("#todoform").submit(function(e){, . , onload() . sendtodo() ?

- , .

+3
2

:

$( "#todoform" ).submit(function(e)

:

$( "#todoform" ).unbind('submit').submit(function(e)
+5

, onload() , . .submit(), onsubmit , .

, alert('anything') sendtodo() , .

:

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

,

+1

Source: https://habr.com/ru/post/1766132/


All Articles