gator
gator

Reputation: 3533

Execute PHP script with AJAX without POST/GET?

I am trying to execute a simple PHP script on click of a <div>. I've searched around SO and some similar questions appear, but all deal with posting data when I have no data to post.

<div name="logout">
    logout
</div>
<script>
    $(document).ready(function() {
        $('div[name="logout"]').click(function() {
            $.ajax({
                url: './scripts/logout.php',
                dataType: 'json'
            }).done(function(result) {
                alert(result.message);
            });
        });
    });
</script>

logout.php is as below:

if (isset($_SESSION["username"]) && (isset($_SESSION["logintoken"]))) {
    session_destroy();
    $jsonArr = array('success' => true, 'message' => "You've logged out.");
    echo json_encode($jsonArr);
} else {
    $jsonArr = array('success' => false, 'message' => "You're not logged in.");
    echo json_encode($jsonArr);
}

No alert is made on click and console shows no errors. Adding a .fail condition to the AJAX call pops every time, but again nothing is in console.

All other times I use AJAX it's to handle forms, not quite this exact circumstance. I have no data to post or get, and most solutions on SO say to add a data: {} bit to the AJAX call, but I'd have nothing to put here.

What have I done wrong here? Tracing through my code, I figured maybe I was reinitializing $_SESSION variables, but I haven't.

Upvotes: 2

Views: 1845

Answers (2)

Maverick
Maverick

Reputation: 945

Try this

<script>
    $(document).ready(function() {
        $('#logoutBtn').click(function() {
            $.ajax({
                url: './scripts/logout.php',
                dataType: 'json'
            }).done(function(result) {
                alert(result.message);
            });
        });
    });
</script>
<div id="logoutBtn">
    logout
</div>

Upvotes: 2

Marc B
Marc B

Reputation: 360922

<div> don't have name. That's for form fields. Try

<div class="logout">
      ^^^^^^^^^^^^
...
        $('div.logout').click(function() {
           ^^^^^^^^^^

instead.

Upvotes: 0

Related Questions