I have spent a long time trying to find a way to do the following:
- Update a MySQL database with AJAX
- Reload the Page to show changes
- Show a success message
I think I have finally found a way! Let me know of any improvements.
The method:
- Make your Ajax call and reload on success
- Set a session in your php code with a variable
- Check the session is set and output the necessary message
- Empty the session
The in-page AJAX call:
$(document).on("click",".active_button",function() {
var articleID = $(this).attr("name");
var active = $(this).val();
$.ajax({
type: "POST",
url: "controllers/articlecontrol.php",
data: { articleID: articleID, active:active },
success: function(data){
document.location.reload(true);
}
});
});
The PHP (articlecontrol.php):
// ACTIVATE / DEACTIVATE w/Button
if(isset($_POST['active'])) {
$active = $_POST['active'];
$articleID = $_POST['articleID'];
if($active == 'YES') {
$update = array('article_active' => '0');
$where = array('article_id' => $articleID);
$sql = $database->update('wcx_articles', $update, $where);
if($sql) {
$_SESSION['status'] = 'deactivated';
}
}
if($active == 'NO') {
$update = array('article_active' => '1');
$where = array('article_id' => $articleID);
$sql = $database->update('wcx_articles', $update, $where);
if($sql) {
$_SESSION['status'] = 'activated';
}
}
}
The success message (in same page as AJAX):
if(isset($_SESSION['status'])) {
if($_SESSION['status'] == 'activated') {
echo '<div class="success">Activated Successfully</div>';
$_SESSION['status'] = '';
}
if($_SESSION['status'] == 'deactivated') {
echo '<div class="success">Deactivated Successfully</div>';
$_SESSION['status'] = '';
}
}