HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Update database, reload page then show a success message

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
showupdatereloadsuccessmessagedatabasepagethen

Problem

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 'Activated Successfully';
        $_SESSION['status'] = '';
    }
    if($_SESSION['status'] == 'deactivated') {
        echo 'Deactivated Successfully';
        $_SESSION['status'] = '';
    }
}

Solution

What you're doing is extremely typical. So typical that a language was made specifically for it: Ajax!

I'll make some comments here, starting from the top.
Your method

It's close, but it can be simplified even more. For reference, here's your 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



and then I'll make my own so we can see the differences.

  • Make an Ajax call



  • Update the database and return a response



  • Output the respective message



A quick re-write

I thought that rewriting this would be the best way to show how things could be done differently.

Ajax

$(".active_button").on("click", function() {

    var articleID = $(this).attr("name");
    var active = $(this).val();
    $.post("controllers/articlecontrol.php", {articleID: articleID, active: active}, function(data) {
        var response;
        var class = "success";
        if (data === "deactivated") {
            response = "Deactivated Successfully";
        } else if (data === "activated") {
            response = "Activated Successfully";
        } else {
            response = "Whoops!";
            class = "failure";
        }
        $("Some DOM item").before('' + response + '').addClass(class);
    });
});


articlecontrol.php

if (isset($_POST['active'])) {
    $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') {
            echo "deactivated";
        } else {
            echo "activated";
        }
    }
}


Inline PHP

Gone! Not even needed anymore!

Changes made:

A lot, right? Well it's okay, I'll try and explain why I modified your code like this.

First off, I placed the button handler directly onto the class and avoided dealing with the document call. It cleared things up a little!

I changed your $.ajax call into a $.post call. For your implementation here, I found it to fit real nice. It's the exact same functionality, just in a way I believe to be more clear and readable.

Inside of this Ajax call, I added a lot of business logic. It now accepts data from the PHP page and then decides how to display the action. The error handler on this is very primitive and could be improved. Note that you must define where in the page the messages will pop up. It appears you have the knowledge to know what I've done here, however if you need me to reference anything or clarify, just ask!

Look at that! Done with the jQuery already!

The biggest change I made with your PHP was taking out the need for sessions. Everything else is simply topical and hopefully more clear than the original code. Let me know if you don't understand anything. Do note however, I have echoed the response that the Ajax will receive. If you needed, you could also format it in JSON, more on that here.

And since we cleared out the sessions, the inline PHP is gone!

I don't normally just rewrite people's code, but I felt this could have used multiple alterations which wouldn't make sense if I din't have complete context!

Code Snippets

$(".active_button").on("click", function() {

    var articleID = $(this).attr("name");
    var active = $(this).val();
    $.post("controllers/articlecontrol.php", {articleID: articleID, active: active}, function(data) {
        var response;
        var class = "success";
        if (data === "deactivated") {
            response = "Deactivated Successfully";
        } else if (data === "activated") {
            response = "Activated Successfully";
        } else {
            response = "Whoops!";
            class = "failure";
        }
        $("Some DOM item").before('<div>' + response + '</div>').addClass(class);
    });
});
if (isset($_POST['active'])) {
    $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') {
            echo "deactivated";
        } else {
            echo "activated";
        }
    }
}

Context

StackExchange Code Review Q#54969, answer score: 2

Revisions (0)

No revisions yet.