Digital Revenge Digital Revenge - 3 years ago 146
jQuery Question

Execute an SQL Query and redirect after successfull execution using AJAX

I have a button (id="deleteAccount"). If the user clicks on it, I want them to be logged out and delete their account from the database and then redirect to the site's homepage. I'm using SESSION to identify the user.

Right now, I'm able to only delete their data from the but not log them out and redirect them to the homepage.

Here's my deleteUserAccount.php

<?php session_start();
if(!isset($_SESSION["username"]))
{
header("Location:blocked.php");
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
}
?>

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$user = $_SESSION["username"];

$deleteSQL = "DELETE FROM `users` WHERE Username='$user'";
$deleteQuery = $conn->query($deleteSQL);

if($deleteQuery) {
unset($_SESSION["username"]);
unset($_SESSION["password"]);
header("Location:index.php");
}
else {
echo "error";
}

?>


And here's my JS file:

$(document).ready(function() {

$('#deleteAccount').click(function() {
$.ajax({
type: "POST",
url: 'deleteUserAccount.php'
});
});

});


THANKS

Answer Source
$.ajax({
            type: "POST",
            url: 'deleteUserAccount.php',
            success : function() {
                $(location).attr('href', 'yoursite/index.php')
            }
        });

You are doing an ajax call here and you redirect user using php thats why user not redirect to the home page. You need to do with client side script in your ajax success callback.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download