1

I am new to jQuery. Basically I have a table which I can sort the rows. I want to save the new order in the backend, which I am able to do. However, I noticed that I am sending multiple Ajax calls depending on the number of times I sorted the table. The order is not saving properly in the backend. Here is my code. The variable order is where the new IDs are stored. I am sending it in my Django through the '/updateorder' route/

<script type="text/javascript">
  $(document).ready(function(){
    $("#sortable").sortable({
      update: function (event, ui) {
        var order = $(this).sortable('toArray');
        console.log(order);

        $(document).on("click", "button", function () {
          $.ajax({
            data: {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, 'order[]': order},
            type: 'POST',
            url: '/updateorder'
          })
        });
      }
    }).disableSelection();
      $('button').on('click', function () {
        var r = $("#sortable").sortable("toArray");
        var a = $("#sortable").sortable("serialize", {
          attribute: "id"
        );
        console.log(r);
      });
    });   
</script>

How can I avoid sending multiple Ajax calls when I click on the button? Also, what is the correct way to redirect to a different page after the logic is executed? Thanks for reading!

PS: I am using python/django in the backend

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Marvin
  • 213
  • 1
  • 3
  • 9
  • You need to cancel previous request if there is another one, try to look here https://stackoverflow.com/questions/19244341/abort-previous-ajax-request-on-new-request – lub0v Sep 22 '17 at 21:48
  • Hello, I tried the code per your link, I made some modifications and I am still sending multiple ajax calls :( – Marvin Sep 22 '17 at 21:58

1 Answers1

3

The answer is in your code. You attach event handler everytime you move item. So when you sort 5 items, you attach 5 event handlers to your submit button. Then when you click the button all 5 event handlers fire ajax call at once. You should move onclick event handler outside and pass variable through function argument or public variable.

bigless
  • 2,849
  • 19
  • 31