1

I am using jquery to send data through ajax to my DB, on success it shows a notification and adds a row to a datatable with the note / info the user just posted.

For some reason it's adding the row twice, instead of just once. Cant figure out why.

My code is :

<script type="text/javascript">
    $(document).ready(function() {
        $('#notestable').DataTable({
            "paging": false,
            "ordering": false,
            "info": false,
            "filter": false
        });    

    $("#addnote").click(function(e) {
      e.preventDefault();
      var note = $("#note1").val();
      var leadid = "<?echo $lead->leadid;?>";
      $.ajax({
        url: "/leads/addnote",
        method: "POST",
        data: {
          note: note,
          leadid: leadid
        },
        success: function(data) {
          $('#closemodal12').trigger('click');
          swal({
            title: "Note added",
            type: "success",
          });

          var notestable1 = $('#notestable').DataTable();

          var lengthToCut = 23;
          var short = note.substr(0, lengthToCut);
          var i = 1;
          var row = $('<tr>');
          row.append('<td>' + short + ' </td>')
            .append('<td><? echo $user->forename;?></td>')
            .append('<td><? echo date('d / m / Y ');?> </td>')
            .append('<td><? echo date('H: i ');?> </td>')
            .append('<td><i class ="fa fa-eye"> </i></td>')
            .append('<td><i class ="fa fa-trash-o"> </i></td>')
          notestable1.row.add(row);
          $('#notestable tbody').prepend(row);



        },
        error: function() {
          alert("Slight problem");
        }
      });
    });
  });

</script>

1 Answer 1

1

Without seeing the markup that goes along with this, it's difficult to be sure, but I believe the problem lies with these two lines of code:

// Append row to notestable1 (already visible in DOM)
notestable1.row.add(row);

// (pre)Append the row again
$('#notestable tbody').prepend(row);

notestable1 appears to be a valid object, already inserted into the DOM, that you're appending the row to. You then append the row again using $('#notestable tbody').prepend(row).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.