Jump to content

Opening SweetAlert in PHP echo


Moorcam
Go to solution Solved by Moorcam,

Recommended Posts

Hi guys,

 

I have this issue. It works fine in another piece of php code as in where I ban a user, it will show sweetalert to confirm and when I click unban this user, it will ask me in a nice sweetalert if I am sure. When I click Yes, the user ban gets lifted and then disaster strikes. It shows a normal js alert with html code inside.

Here is the code that is used to lift the ban:

<?php
include_once('config.php');

// Function to unban a user
function unbanUser($userId) {
    global $conn;

    // Prepare the SQL statement securely
    $stmt = $conn->prepare("UPDATE users SET status = ? WHERE user_id = ?");
    $status = 'Active';
    $stmt->bind_param("si", $status, $userId);
    
    // Execute the statement and handle the result
    if ($stmt->execute()) {
        echo '<script>Swal.fire("Success", "User has been unbanned.", "success");</script>';
    } else {
        echo '<script>Swal.fire("Error", "Error removing user ban: ' . htmlspecialchars($stmt->error) . '", "error");</script>';
    }
    
    $stmt->close();
}

// Check if the request is made via POST and validate user input
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['userId'])) {
    $userId = filter_input(INPUT_POST, 'userId', FILTER_VALIDATE_INT);
    
    if ($userId !== false) {
        unbanUser($userId);
    } else {
        echo '<script>Swal.fire("Invalid Input", "Invalid user ID.", "warning");</script>';
    }
}

?>

Just confirming, I do have Sweetalert script included in the header (because it needs to be before any execution).

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

If anyone can work this out I would appreciate it.

Thank you :)

Link to comment
Share on other sites

8 hours ago, requinix said:

There's nothing in here that should show a normal Javascript alert()...

I know. It's not meant to. It's meant to show a Sweetalert, hence the Swal.fire instead of alert. Problem is, it IS showing a normal JS alert on this line:

echo '<script>Swal.fire("Success", "User has been unbanned.", "success");</script>';

But, the JS Alert has this in it:

'<script>Swal.fire("Success", "User has been unbanned.", "success");</script>'

 

js-alert.png

Edited by Moorcam
Link to comment
Share on other sites

The code you posted is not using alert().

Is it possible that the code you posted is meant to return a message to display? And since you're returning a message that looks like HTML, it is alert()ing that HTML? If so then the code you need to fix isn't what you posted...

Link to comment
Share on other sites

5 minutes ago, requinix said:

The code you posted is not using alert().

Is it possible that the code you posted is meant to return a message to display? And since you're returning a message that looks like HTML, it is alert()ing that HTML? If so then the code you need to fix isn't what you posted...

For sweetalert to work, it replaces the alert part with Swal.fire So like so:

<script>alert("Normal JS Alert");</script>
<script>Swal.fire("Are you sure?","You are about to unban this user","warning");</script>

See attached image

Reference:

https://sweetalert.js.org/

swal-alert.png

Edited by Moorcam
Link to comment
Share on other sites

  • Solution

Fixed.

The issue was with the Javascript:

// Unban User
function unbanUser(userId) {
    Swal.fire({
        title: 'Are you sure?',
        text: "You are about to unban this user.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, unban it!',
        cancelButtonText: 'No, cancel!',
    }).then((result) => {
        if (result.isConfirmed) {
            fetch("includes/unban-user.php", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `userId=${encodeURIComponent(userId)}`
            })
            .then(response => handleResponse(response))
            .catch(error => {
                console.error("Error:", error);
                Swal.fire({
                    title: 'Error!',
                    text: 'There was an issue unbanning the user.',
                    icon: 'error',
                    confirmButtonText: 'Okay'
                });
            });
        }
    });
}

function handleResponse(response) {
    if (response.ok) {
        response.text().then(text => {
            Swal.fire({
                title: 'Success!',
                text: text,
                icon: 'success',
                confirmButtonText: 'Okay'
            }).then(() => {
                location.reload(); // Reload the page to see the changes
            });
        });
    } else {
        console.error("Error: " + response.statusText);
        Swal.fire({
            title: 'Error!',
            text: 'There was an issue unbanning the user.',
            icon: 'error',
            confirmButtonText: 'Okay'
        });
    }
}

I was missing this part:

function handleResponse(response) {
    if (response.ok) {
        response.text().then(text => {
            Swal.fire({
                title: 'Success!',
                text: text,
                icon: 'success',
                confirmButtonText: 'Okay'
            }).then(() => {
                location.reload(); // Reload the page to see the changes
            });
        });
    } else {
        console.error("Error: " + response.statusText);
        Swal.fire({
            title: 'Error!',
            text: 'There was an issue unbanning the user.',
            icon: 'error',
            confirmButtonText: 'Okay'
        });
    }
}

Thanks for your help regardless. Always appreciated.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.