I try to make this form: id / name, by submit the record is added to the database and reproduced on the page. The record itself has a delete button, which should be deleted from the database, and, accordingly, from the page. Actions are performed via AJAX requests, and a problem occurs. There is a JS code: a function that displays all records from the database, the function add handler, the function delete handler.
function showAllRecords() { $.ajax({ url: 'showallrecords.php', success: function(html) { $('#records').html(html); } }); return false; } showAllRecords(); $('#addrecord').submit( function() { var form = $(this).serialize(); $.ajax({ type: 'POST', url: 'newobj.php', data: form }); showAllRecords(); return false; } ); $('#deleteRecord').submit( function() { var form = $(this).serialize(); $.ajax({ type: 'POST', data: form, url: 'deleteobj.php' }); showAllRecords(); return false; } );
PHP script add entries to the database:
<?php require_once('login.php'); $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database); if ($connection->error) die($connection->error); $id = $_POST['id']; $name = $_POST['name']; $query = "insert into test values('$id','$name')"; $result = $connection->query($query); if (!$result) die($connection->error); ?>
PHP script to delete the record:
<?php require_once('login.php'); $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database); if ($connection->error) die($connection->error); $id = $_POST['id']; $name = $_POST['name']; $query = "insert into test values('$id','$name')"; $result = $connection->query($query); if (!$result) die($connection->error); ?>
PHP script that displays all entries on the page:
<?php require_once('login.php'); $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database); if ($connection->error) die($connection->error); $query = "select * from test"; $result = $connection->query($query); if (!$result) die($connection->error); $rows = $result->num_rows; for ($i = 0; $i < $rows; $i++) { $result->data_seek($i); $row = $result->fetch_array(MYSQLI_NUM); echo <<<_END <div class="aRecord"> id: $row[0] <br> name: $row[1] <br> <form id="deleteRecord"> <input type="hidden" name="deletingRecordID" value="$row[0]"> <input type="submit" value="delete"> </form> </div> _END; } ?>
The question is as follows. Adding and playing records happens without problems, everything works as it should, but the delete handler function, which is called by the button added by the PHP script, does nothing at all. Moreover, if you add a similar form to the HTML code yourself and try to delete some arbitrary record from the database, everything works. Why does the script added form not work?
$('#deleteRecord').submit( function() {
use$(document).on('submit', '#deleteRecord', function(){
. Similarly with addrecord - Alexey Shimansky$query = "insert into test values('$id','$name')";
- xaja