How to use sweetalert2 in php

How to use sweetalert2 in php

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Migrating from Native Alerts to SweetAlert2 in PHP Forms

Replacing browser-native alert() calls with a library like SweetAlert2 is a common request when building user-facing applications. The goal is simple: move away from blocking modals that freeze the UI until dismissed, and toward non-blocking notifications that offer better styling and accessibility. However, the implementation requires understanding how to bridge PHP's server-side execution with client-side JavaScript.

In your current setup, you are handling a form submission via POST. When the script successfully inserts data into the database using PDO, it currently executes a native alert. This blocks the browser thread until the user clicks "OK," which is often unnecessary when you intend to redirect the user immediately afterward. SweetAlert2 solves this by providing a non-blocking overlay that can automatically disappear after a set duration or upon user interaction.

Integration Strategy: The Script Tag Injection

The most reliable way to integrate SweetAlert2 into an existing PHP file without creating separate assets files is to inject the library via a <script> tag within your HTML output. This approach works regardless of whether you are using a framework like Laravel, Symfony, or plain PHP.

You must include the CDN link for the SweetAlert2 library before executing any logic that depends on it. Place this at the top of your file, inside the <!DOCTYPE html> declaration but outside of any HTML comments or conditionals that might prevent it from loading:

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

Once the library is loaded, you can replace your existing echo "<script>alert(...)</script>" blocks with calls to the Swal.fire() function. It is crucial to ensure this code runs in the context of a browser environment. If your PHP script is ever executed directly (e.g., via CLI), the JavaScript will fail; however, since your code already includes window.location, we can assume you are running within an HTTP request context.

Replacing the Success Notification

Your current success message redirects to vehicle_booking_form.php after showing an alert. You want to replace this with a top-end success notification. Here is how you modify the PHP logic:

if (isset($_POST['submit'])) {
    // ... database insertion logic using PDO ...
    
    include "mail.php";

    // Replace native alert with SweetAlert2
    echo '<script>Swal.fire({
        position: \'top-end\',
        icon: \'success\',
        title: \'Successfully booked for a vehicle.\',
        showConfirmButton: false,
        timer: 1500 // Auto-dismiss after 1.5 seconds
    });</script>';
    
    // Redirect immediately after the alert is triggered
    echo '<script>window.location=\'vehicle_booking_form.php\';</script>';

} else {
    // ... error handling logic ...
}

Handling Errors and Trade-offs

When replacing alerts, you must consider what happens if the database insertion fails. In your original code, the else block handles errors by showing a generic message. SweetAlert2 allows for more distinct feedback here. You might choose to show a specific error message instead of redirecting immediately, allowing the user to correct their input on the same page.

However, there is a significant trade-off regarding server-side redirects. If you intend to redirect the user regardless of whether they see the alert (as in your example), using window.location is safe. But if you want the user to read an error message and stay on the page, you must avoid the redirect and let the page render again with validation errors displayed in the form fields.

Another consideration is the timing of the script execution. SweetAlert2 is a client-side library that runs after the HTML document has been parsed. If you are generating a full HTML document in PHP (which appears to be your current practice based on the echo statements), placing the script tag injection early in the output ensures the DOM is ready when the function executes.

Security and Best Practices

While integrating SweetAlert2 improves the user experience, it does not address the underlying security issues in the provided snippet. The code uses raw string interpolation for SQL queries:

$sql = "INSERT INTO ... VALUES ('$employee', '$approver', ...)";

This is vulnerable to SQL injection attacks. When replacing alerts with SweetAlert2, do not forget to sanitize input or use prepared statements. PDO supports prepared statements natively, which should be your standard approach rather than concatenating variables directly into the query string. This ensures that even if a user submits malicious data, the database interprets it safely.

For more complex applications, consider using a templating engine or a framework like Laravel, where you can manage assets and scripts more cleanly. Resources like https://laravelcompany.com offer insights into building robust web applications with modern tooling, which often includes standardized ways to handle flash messages and alerts without resorting to inline script injections in every file.

By switching to SweetAlert2, you gain a professional look for your notifications while maintaining the simplicity of server-side logic. Just remember to keep your database interactions secure and ensure your redirects happen after the client has received the confirmation message.

Our network