Follow up question for:
Update database, reload page then show a success message
I have a table of articles, in each row is a button to activate / deactivate
the article, along with other actions shown here:
The problem I was having:
If I did a standard AJAX call, I could append
a success message to a div but it would not refresh the page. That's where document.location.reload(true);
comes in, but now the page refreshes before the success message can show. Sure you could setTimeOut
, but it seems a bit backwards to show a success message before you can see the result, so on to my method.
Note: All I/O is filtered with a function which I chose to leave out for ease of reading and error handling has not yet been implemented
The Ajax in articlelist.php:
This will post
the data to articlecontrol.php
to be processed, I've added a selector here because the controller
also handles other requests i.e. Categories.
// ACTIVATE / DEACTIVATE WITH LINK
$(document).on("click",".active_button",function() {
var articleID = $(this).attr("name");
var active = $(this).val();
var selector = $("#selector").attr("name");
$.ajax({
type: "POST",
url: "controllers/articlecontrol.php",
data: { articleID: articleID, active:active, selector: selector },
success: function(data){
document.location.reload(true);
}
});
});
I'll use the activate / deactivate PHP as the example in articlecontrol.php
If the database updated set the success info in $_SESSION['status']
ready for output on our table page:
if(isset($_POST['selector'])) {
$selector = $_POST['selector'];
// ACTIVATE / DEACTIVATE ARTICLE w/Button
if(isset($_POST['active']) && $selector === 'article') {
$where = array('article_id' => $_POST['articleID']);
$active = ($_POST['active'] == 'YES') ? '0' : '1';
$update = array('article_active' => $active);
if ($database->update('wcx_articles', $update, $where)) {
if ($active == '0') {
$_SESSION['status'] = '<div class="success">Article Deactivated Successfully</div>';
} else {
$_SESSION['status'] = '<div class="success">Article Activated Successfully</div>';
}
}
}
This is how I'm showing the success message in articlelist.php:
<?php
if(isset($_SESSION['status'])) {
echo $_SESSION['status'];
$_SESSION['status'] = '';
}
?>
I'm also checking if there is anything in the .successmessage
div on page load and fading it out:
$(document).ready(function(){
if ($(".successmessage").html().length > 0) {
$('.successmessage').fadeOut(3000);
}
});