Example use ajax request of SweetAlert

Since SweetAlert is promise-based, it makes sense to pair it with AJAX functions that are also promise-based. Below is an example of using fetch to search for artists on the iTunes API. Note that we're using content: "input" in order to both show an input-field and retrieve its value when the user clicks the confirm button

Example :

 

<!DOCTYPE html>

<html>

    <body>

        <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

        <p>Example Alert use ajax</p>

 

        <button onclick="run()">Run</button>

 

        <script>

            function run() {

               swal({

                  text: 'Search for a movie. e.g. "La La Land".',

                  content: "input",

                  button: {

                    text: "Search!",

                    closeModal: false,

                  },

                })

                .then(name => {

                  if (!name) throw null;

 

                  return fetch(`https://itunes.apple.com/search?term=${name}&entity=movie`);

                })

                .then(results => {

                  return results.json();

                })

                .then(json => {

                  const movie = json.results[0];

 

                  if (!movie) {

                    return swal("No movie was found!");

                  }

 

                  const name = movie.trackName;

                  const imageURL = movie.artworkUrl100;

 

                  swal({

                    title: "Top result:",

                    text: name,

                    icon: imageURL,

                  });

                })

                .catch(err => {

                  if (err) {

                    swal("Oh noes!", "The AJAX request failed!", "error");

                  } else {

                    swal.stopLoading();

                    swal.close();

                  }

                });

            }

        </script>

 

    </body>

</html>

 

Input : La La

 

 

Result: