0

Introduction: I am doing a server-side Jquery datatables.net library using ajax/json. My sample project can be found: https://databasetable-net.000webhostapp.com/

Error: When I click the delete button.... The console shows "Uncaught RangeError: Maximum call stack size exceeded". It looks to me as though the Ajax call isn't being issued (nothing is showing on the network tab) - so it must be when creating the request. I suspect I need to JSON.stringify my del_id.

Index.php Code:

<script type="text/javascript">
$(document).ready(function() {
     $( "#form1" ).hide();
        $( "#signup" ).click( function() {
        $( "#form1" ).toggle( 'slow' );
        });     
});     
</script>

<script type="text/javascript">
$(document).ready(function() {
var table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "server.php",
"type": "POST",
},

columnDefs: [{
targets: -1,
defaultContent: '<button type="button" class="delete_btn" data-id=<?php echo "row[id]"?> ">Delete</button>  <button type="button" class="edit_btn">Edit</button>'
}],
rowGroup: {
dataSrc: 1
}
});
});
</script>

<script type="text/javascript"> 
$(function(){
        $(document).on('click','.delete_btn',function (e) {
           e.stopPropagation();
        var per_id=$(this).data('id');
        var del_id= $(this).closest('tr');
        var ele = $(this).parent().parent();  
        console.log(del_id);

        $.ajax({
            type:'POST',
            url:'delete.php',
            dataType: 'json', //This says I'm expecting a response that is json encoded.
            data: { 'del_id' : del_id}, 

            success: function(data){ //data is an json encoded array.

              console.log('Data: ' + data); 
               console.log(JSON.stringify('Data: ' + data)); 

              if(data['success']){  //You are checking for true/false not yes or no.
                console.log('You successfully deleted the row.');
                alert("row deleted");
                ele.remove();
              }else{
                console.log('The row was not deleted.');
                }

            }
        });
        });
</script>

<script type="text/javascript">  
          $(document).on('click', '.edit_btn',function(){
            var edit_id= $(this).closest('tr');
        var ele = $(this).parent().parent();  //removed the "$" from the ele variable. It's a js variable.
        console.log(edit_id);
            $('#content-data').html('');
            $.ajax({
                url:'edit.php',
                type:'POST',
               data: { 'edit_id' : edit_id}, 
                dataType:'html'
            }).done(function(data){
                $('#content-data').html('');
                $('#content-data').html(data);
            }).fail(function(){
                $('#content-data').html('<p>Error</p>');
            });
});
 </script>

Delete.php

$del_id = $_POST['del_id']; 
$stmt = $con->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();

$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
  $array['success'] = TRUE;
}

    echo json_encode($array); //Your ajax is setup to expect a json response.  
    //json_encode the $array and echo it out.  You have to do this.  
    //When you "echo" out a value, that is what the server is going to submit back to the ajax function.
    //If you do not do this, the ajax script will not recieve a response from the delete.php page.

What I have tried: I tried using stringify.json within the delete.php page with no success.

  $array=JSON.stringify($array);
    echo json_encode($array);

This seemed to have gotten rid of the Uncaught RangeError: Maximum call stack size exceeded error:

  $(document).on("click", ".remove-discount-button", function (e) {
               e.stopPropagation();
               //some code
            });

Maximum call stack size exceeded error

  • 1
    `JSON.stringify` is a javascript operation, not php – charlietfl Sep 03 '18 at 03:03
  • 2
    Shouldn't create new event listeners inside other event handlers. Move the ones you create for delete and edit buttons inside `$('#signup').click..` outside of that event handler function – charlietfl Sep 03 '18 at 03:07
  • i put this in its own jquery to make it less confusing. –  Sep 03 '18 at 03:38
  • i agree on both. let me take a look at your solution which looks very helpful. –  Sep 03 '18 at 03:38

2 Answers2

0

The main stack problem is caused by var edit_id = $(this).closest('tr'); . You try to send that whole jQuery object as data in the ajax. Then jQuery can't serialize it internally and throws a fit

You probably want some property like ID or a data attribute from that row to send (not clear what expectations are)

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • If i am understanding this correctly, you cannot use $(this) and serialize it to ajax. ok. i will try the data-attribute way which i am familiar with... –  Sep 03 '18 at 04:02
  • A jquery object contains functions which won't serialize and cause error when you try to do it – charlietfl Sep 03 '18 at 15:30
  • ahh because this.closest is always changing depending on the click. where as data-attribute is already set in stone. think i get the very basics. thx. –  Sep 03 '18 at 17:15
  • No...you want a value from the element (or from somewhere inside the element)...not the element itself. It's as simple as that – charlietfl Sep 03 '18 at 18:01
  • Found an old project of mine. Looks like I have to do this: $(document).on('click', 'columm_sort', function()){ var column_name =$(this).attr("id"); var order = $(this).data("order"); var arrow=''; if (order=='desc'){ arrow= ''; } else { arrow= ''; } $.ajax({ url:"index.php", method:"POST", data:{column_name:column_name, order:order}, success:function(data){ alert("ajax worked"); } }); //end AJAX }); //end document ready –  Sep 03 '18 at 19:39
0

Ok. So using the above example probably does not work using the Jquery datatables.net library (but would work for a regular datatable). Instead you have to use render: https://datatables.net/reference/option/columns.render

I posted on their forums and got a quick example:http://live.datatables.net/qemodapi/1/edit

Here is the full code that I made myself that is working:

    <script type="text/javascript"> 
        $(document).on('click','.delete_btn',function (){
    var id = $(this).attr("id").match(/\d+/)[0];
  var del_id = $('#example').DataTable().row( id ).data();
  var del_id = del_id[0];
  console.log(del_id[0]); 
        $.ajax({
            type:'POST',
            url:'delete.php',
            dataType: 'json', //This says I'm expecting a response that is json encoded.
            data: { 'del_id' : del_id}, 
            success: function(data){ 
              if(data['success']){  //You are checking for true/false not yes or no.
                console.log('You successfully deleted the row.');
              }else{
                console.log('The row was not deleted.');
                }
                }
        });
        });
</script>