sweetalert js full code with code examples

SweetAlert is a popular JavaScript library for creating customizable and responsive alerts. It is easy to use and provides a lot of flexibility for developers. This library became very popular for creating beautiful alert boxes and pop-up dialogs that can help to provide feedback to the user. In this article, we will discuss the SweetAlert JS full code with code examples.

Getting started with SweetAlert JS

Before diving into the SweetAlert JS full code, it is important to know how to get started with SweetAlert, which is very easy. Firstly, we need to download SweetAlert JS from the official website or from the GitHub repository. After that, we need to include these files in our HTML file.

<!-- SweetAlert CSS -->
<link rel="stylesheet"
     href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" />

<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- SweetAlert JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

Once the files are included in the HTML file, we can start using SweetAlert in our code.

SweetAlert JS Full Code

Now, let's discuss the SweetAlert JS full code by explaining each component of it. Here is the code snippet for a Simple Alert:

swal("Hello World!");

This code snippet will display an alert box with the message "Hello World!" as the title of the box.

Here is the code snippet for an Alert with a Message:

swal("Hello world!", "This is a message", "success");

This code snippet will display a success alert with the message "This is a message" as the body of the alert box.

Here is the code snippet for An Alert with a Custom Image:

swal({
    title: "Custom Image",
    text: "This is a custom image",
    imageUrl: "https://unsplash.it/400/200/?random",
    imageWidth: 400,
    imageHeight: 200,
    imageAlt: "Custom image",
});

This code snippet will display an alert box with a custom image.

Here is the code snippet for a Prompt:

swal({
    title: "Submit your Name",
    text: "Enter your name:",
    content: "input",
    button: {
        text: "Submit",
        closeModal: true,
    },
    icon: "info",
    dangerMode: true,
}).then((name) => {
    swal(`Hello ${name}!`);
});

This code snippet will display a prompt box for entering the name and will show the message "Hello ${name}!" after the prompt box gets closed.

Here is the code snippet for an AJAX call:

swal({
    title: "Do you want to proceed?",
    text: "This action cannot be undone!",
    icon: "warning",
    buttons: ["Cancel", "Proceed"],
    dangerMode: true,
}).then((willDelete) => {
    if (willDelete) {
        $.ajax({
            url: "delete.php",
            type: "POST",
            data: { id: id },
            success: function (data) {
                swal("Deleted!", "Your file has been deleted!", "success");
            },
            error: function (data) {
                swal("Oops...", "Something went wrong!", "error");
            },
        });
    } else {
        swal("Your file is safe!");
    }
});

This code snippet will display a warning message with cancel and proceed buttons. If the user presses Proceed, the AJAX call will get executed and will show a success message. If the user clicks on Cancel, nothing will happen, and the alert box will get closed.

SweetAlert JS Code Examples

Now, let's see some code examples on how to use SweetAlert JS in different scenarios, which is discussed in the following sections.

SweeAlert JS for Form Submission

$("form").submit(function (e) {
    e.preventDefault();
    swal("Do you want to submit the form?", {
        buttons: {
            cancel: true,
            confirm: {
                text: "Yes, submit",
                closeModal: false,
            },
        },
    }).then((value) => {
        if (value) {
            e.target.submit();
        } else {
            swal("Your form is safe!");
        }
    });
});

This code snippet will display an alert box with cancel and submit buttons for form submission.

SweetAlert JS for Errors

$.ajax({
    url: "https://jsonplaceholder.typicode.com/todos/",
    type: "GET",
    dataType: "json",
    success: function (data) {
        console.log("Success");
    },
    error: function (jqXHR, textStatus, errorThrown) {
        swal({
            title: "Error!",
            text:
                "An error occurred. Please try again later. Error Code: " +
                errorThrown,
            icon: "error",
            button: "OK",
        });
    },
});

This code snippet will display an error message with an error code (if any) in case of any error.

SweeetAlert JS for Success Messages

$.ajax({
   url: "api/create.php",
   type: "POST",
   data: postData,
   success: (res)=>{
       swal("Success", "Your record has been created", "success");
   },
   error: function (res) {
       swal("Error!", "An error occurred during record creation", "error");
   },
});

This code snippet will display a success message after the record is created successfully.

Conclusion

SweetAlert JS is a very useful JavaScript library that allows us to create beautiful and responsive alert boxes with a lot of customization options. We showcased some of the most common examples of using SweetAlert JS in different scenarios. So, if you want to make your website's alert box more visually appealing and user-friendly, SweetAlert JS is a great choice.

let me provide more details on the previous topics discussed in the article.

Getting started with SweetAlert JS

To get started with SweetAlert JS, we first need to download the library either from the official website or from the GitHub repository. Once we have the files, we can include the SweetAlert CSS and JS files in our HTML code. Besides, we also need to include the jQuery library, which is a requirement for using SweetAlert JS.

After including these files, we need to call the SweetAlert function and pass the options that we want to display in the alert box. The SweetAlert function can be called with a few different parameters. The first parameter is the title of the alert box, the second parameter is the text that appears inside the box, and the third parameter is the type of alert box (e.g., success, error, warning). You can also pass additional parameters such as buttons, icons, etc.

Here’s an example of how you can create a basic alert box with SweetAlert JS:

swal("Welcome to SweetAlert JS!");

This code snippet will display an alert box with "Welcome to SweetAlert JS!" as the title of the box.

Code Examples

The article also discussed some SweetAlert JS code examples that you can use in different scenarios. For instance, when creating a form, you may want to prompt users before they submit the form to make sure that they want to submit it. In this scenario, you can use the following code to create an alert box with cancel and submit buttons:

$("form").submit(function (e) {
    e.preventDefault();
    swal("Do you want to submit the form?", {
        buttons: {
            cancel: true,
            confirm: {
                text: "Yes, submit",
                closeModal: false,
            },
        },
    }).then((value) => {
        if (value) {
            e.target.submit();
        } else {
            swal("Your form is safe!");
        }
    });
});

This code will prevent the form from submitting until the user confirms that they want to submit it.

Another scenario discussed in the article is using SweetAlert JS for errors. In case of any error, it's important to inform the user about the issue. The following code can be used to display an error message with an error code (if any):

$.ajax({
    url: "https://jsonplaceholder.typicode.com/todos/",
    type: "GET",
    dataType: "json",
    success: function (data) {
        console.log("Success");
    },
    error: function (jqXHR, textStatus, errorThrown) {
        swal({
            title: "Error!",
            text:
                "An error occurred. Please try again later. Error Code: " +
                errorThrown,
            icon: "error",
            button: "OK",
        });
    },
});

This code snippet will display an error message with an error code (if any) if there is an error in the AJAX call.

Conclusion

SweetAlert JS is a powerful library that allows us to create beautiful and responsive alert boxes with ease. It provides a lot of customization options and can be used in different scenarios. In this article, we discussed how to get started with SweetAlert JS, and provided some code examples that can be used to create alert boxes for various scenarios.

Popular questions

  1. What is SweetAlert JS and what is it used for?

Answer: SweetAlert is a popular JavaScript library used for creating customizable and responsive alerts and pop-up dialogs. It is easy to use and provides a lot of flexibility for developers, making it popular for creating visually appealing feedback boxes.

  1. Is it necessary to include jQuery for using SweetAlert JS?

Answer: Yes, it is necessary to include jQuery along with the SweetAlert CSS and JS files for using the library.

  1. How can we create a simple alert box using SweetAlert JS?

Answer: We can create a simple alert box using SweetAlert JS by calling the swal() function and passing the message as the parameter. For example, swal("Hello World!"); will display an alert box with "Hello World!" as the title.

  1. How can we create an alert box with custom image using SweetAlert JS?

Answer: We can create an alert box with a custom image using SweetAlert JS by passing the imageUrl parameter along with the other options in the swal() function. For example,

swal({
    title: "Custom Image",
    text: "This is a custom image",
    imageUrl: "https://unsplash.it/400/200/?random",
    imageWidth: 400,
    imageHeight: 200,
    imageAlt: "Custom image",
});

will display an alert box with a random image from Unsplash as the custom image.

  1. How can we use SweetAlert JS for form submission?

Answer: We can use SweetAlert JS for form submission by adding an event listener for the form submit button. When the button is clicked, we can display an alert box asking if the user wants to submit the form. Based on the user's response, we can submit the form or cancel the submission. For example,

$("form").submit(function (e) {
    e.preventDefault();
    swal("Do you want to submit the form?", {
        buttons: {
            cancel: true,
            confirm: {
                text: "Yes, submit",
                closeModal: false,
            },
        },
    }).then((value) => {
        if (value) {
            e.target.submit();
        } else {
            swal("Your form is safe!");
        }
    });
});

will prompt the user to confirm if they want to submit the form and then proceed with submission or cancel it based on their response.

Tag

Snippets

Cloud Computing and DevOps Engineering have always been my driving passions, energizing me with enthusiasm and a desire to stay at the forefront of technological innovation. I take great pleasure in innovating and devising workarounds for complex problems. Drawing on over 8 years of professional experience in the IT industry, with a focus on Cloud Computing and DevOps Engineering, I have a track record of success in designing and implementing complex infrastructure projects from diverse perspectives, and devising strategies that have significantly increased revenue. I am currently seeking a challenging position where I can leverage my competencies in a professional manner that maximizes productivity and exceeds expectations.
Posts created 3193

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top