I need to update the content of my td which have unique id after an ajax update.
However my approach doesnt work, the ajax is succesful but td will only update after page reload.
$(document).ready(function(){
$('body').on('click', '.editButton', function(e){
var postID = $(this).val();
var postURL = "../Controller/update.php";
var postNama = $("#nama"+postID).val();
var postMSISDN = $("#msisdn"+postID).val();
var postSMS = $("#sms"+postID).val();
$.ajax({
type: "POST",
url: postURL,
data:
{
nama: postNama,
msisdn: postMSISDN,
sms: postSMS,
id: postID
},
success: function(data){
$("#nama"+postID).html(postNama);
$("#msisdn"+postID).html(postMSISDN);
$("#sms"+postID).html(postSMS);
}
});
e.preventDefault();
});
});
the html i echoed :
<tr id='tr".$data['id']."'>
<td>".$data['id']."</td>
<td id='nama".$data['id']."'>".$data['nama']."</td>
<td id='msisdn".$data['id']."'>".$data['msisdn']."</td>
<td id='sms".$data['id']."'>".$data['sms']."</td>
<td><button type='button' class='btn btn-default' data-toggle='modal' data-target='#editModal".$data['id']."'>Edit</button></td>
<td><button type='button' class='btn btn-danger' data-toggle='modal' data-target='#deleteModal".$data['id']."'>Delete</button></td>
</tr>
update.php :
<?php
require_once "../Model/Model.php";
$nama = $_POST["nama"];
$msisdn = $_POST["msisdn"];
$sms = $_POST["sms"];
$id = $_POST["id"];
updateData($nama, $msisdn, $sms, $id);
?>
model.php :
function updateData($nama, $msisdn, $sms, $id){
try{
$conn = new PDO('mysql:host=localhost; dbname=crud', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
$conn->prepare("UPDATE data SET nama = ?, msisdn = ?, sms = ? WHERE id = ?")->execute([$nama, $msisdn, $sms, $id]);
}