Abhijit Borkakoty Abhijit Borkakoty - 5 months ago 10
jQuery Question

Delete record from a dynamically created form using ajax and php

I want to delete the records that are dynamically created but the code is not working..Please have a look

script.js

$(function() {

$('#studentRecord').on('click', 'button.delete', function() {

var $tr = $(this).closest('tr');

var $id = parseInt( $(this).attr('id').split('-')[1] );


if ( confirm("Are you sure you want to delete this record") ) {

$.ajax({
url: '/ab_batch/practice/db/action.php',
type: 'POST',
data: {
action: 'ajaxDelRecord',
id: JSON.stringify(id)
},

success: function() {},


error: function() {}

});

}


});


});


action.php

$action = ( isset($_REQUEST['action']) && !empty($_REQUEST['action']) ) ? $_REQUEST['action'] : null;
switch ($action) {
case 'ajaxDelRecord':

if ( isset($_POST['id']) ) {
$id = json_decode($_POST['id']);
}

$id = json_decode($_POST['id']);
print ( $student->delRecord($id) ) ? 'true' : 'false' ;

break;

}


There is another file db.php that contains all the APIs for delete, add and update

Answer

JSON.stringify(id) should be JSON.stringify($id) as you are declaring your id as $id , you don't really need : JSON.stringify as you are just sending an integer to the server.

and for deleting the line which you just removed from database , you can just replace your javascript code with following:

$(function() {

            $('#studentRecord').on('click', 'button.delete', function() {

            var $tr = $(this).closest('tr');

            var $id = parseInt( $(this).attr('id').split('-')[1] );


            if ( confirm("Are you sure you want to delete this record") ) {

                $.ajax({
                    url: '/ab_batch/practice/db/action.php',
                    type: 'POST',
                    data: {
                        action: 'ajaxDelRecord',
                        id: JSON.stringify($id)
                    },

                    success: function() {},

                      $tr.remove(); // removing the current deleted record from html.
                    error: function() {}

                });

            }


        });


    });

i did add $tr.remove(); inside a success callback , as you have already declared the parent element of the deleted record , so you just need to use : $tr.remove(); to delete the tr.

Comments