php - how to handle mysql update error using ajax
one text
Solution:
Tweak the PHP & HTML so that the nesting is correct and assign a new dataset attribute to the button rather than the inline event handler.
<?php
$root = realpath(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) );
include ($root . '/insights/ss/onix.php');
$result = mysqli_query($mysqli,"select * from notifications where seen = 0");
if ($result){
if($result->num_rows) {
while($row = mysqli_fetch_assoc($result)){
?>
<div class='alert alert-success alert-dismissible' role='alert' style='margin-left:-12px;'>
<button type="button" class="close" data-id="<?=$row['id'];?>" data-dismiss="alert" aria-label="Close" style="float:left!important; border:0; background:none;">
<span aria-hidden="true">×</span>
</button>
<strong>
<span class="text-success" style="margin-top:-50px;">
<i class='fa fa-check'></i>
File has been moved successfully
</span>
</strong>
<br>
To confirm reading this message please press X button
</div>
<?php
}
}
}
?>
Use an externally registered event handler and why not use the fetch
api ~ appears slightly shorter and is a better api moving forwards.
<script>
function updateId(e){
e.stopPropagation();
let id=e.target!=e.currentTarget ? e.target.parentNode.dataset.id : e.target.dataset.id;
fetch( 'dismisssuccess.php?id='+id )
.then(r=>r.text())
.then(text=>console.log(text))
}
document.querySelectorAll('div[role="alert"] button[data-id]').forEach(bttn=>bttn.addEventListener('click',updateId))
</script>
Within the PHP you really, really should use a prepared statement
when dealing with user supplied data - otherwise all your hard work could be undone by one malicious user!
<?php
if( !empty( $_GET['id'] ) ){
$id = $_GET['id'];
$ip = getenv('REMOTE_ADDR');
$root = realpath(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) );
include ($root . '/insights/ss/onix.php');
$sql='UPDATE `notifications` SET `seen`=1, `seenby`=? where `id`=?';
$stmt=$mysqli->prepare($sql);
$stmt->bind_param('ss',$ip,$id);
$stmt->execute();
$rows=$stmt->affected_rows;
$stmt->close();
exit( $rows ? 'Success' : 'There is some error' );
}
?>
Source