3
\$\begingroup\$

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'] = '';
    }
}
\$\endgroup\$
  • \$\begingroup\$ Should have mentioned that i sanitise my I/O with a function but left it out for cleaner reading \$\endgroup\$ – CodeX Jun 22 '14 at 20:20
1
\$\begingroup\$

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('<div>' + response + '</div>').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!

\$\endgroup\$
  • \$\begingroup\$ Will this refresh the page to show changes ? \$\endgroup\$ – CodeX Jun 26 '14 at 22:34
  • \$\begingroup\$ When the data is loaded, it does logic and then adds the div in the page! There's no refreshing, but there is dynamic updating \$\endgroup\$ – Alex L Jun 26 '14 at 22:41
  • \$\begingroup\$ I will update my question and provide some reasoning behind the page refresh and why it took me a while to come up with this method. I really like your use of shorthand here and I will try the php switch you have implemented as it cuts my php code in half, thanks \$\endgroup\$ – CodeX Jun 26 '14 at 23:04
  • \$\begingroup\$ If you write up new code, its usually best to start a new question and reference the old one if you want a new review :) \$\endgroup\$ – Alex L Jun 26 '14 at 23:07
  • \$\begingroup\$ I will tag you in the new question, my original question wasn't as clear as I initially thought, I will explain the situation that I am using this in and hopefully that will make things clearer for you. \$\endgroup\$ – CodeX Jun 26 '14 at 23:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.