Discovering the ways to retrieve Axios response within a SweetAlert2 confirmation dialog

I'm struggling to grasp promises completely even after reviewing https://gist.github.com/domenic/3889970. I am trying to retrieve the response from axios within a sweetalert confirmation dialog result.

Here is my current code:

axios
    .post("/posts", this.formData)
    .then(response => {
        if (typeof response.data.callback !== "undefined") {
            toastr.info("Created");
            swal.fire({
                title: "Success!",
                text: "you created new post",
                type: "success",
                showConfirmButton: true,
                confirmButtonText: "Close this",
                allowOutsideClick: false
            }).then(result => {
                if (result.value) {
                    window.location.replace(response.data.callback);
                }
            });;
        } else {
            toastr.error("Can't process this request");
        }
        this.formLoading = false;
    })

The response variable returns as undefined, indicating that there might be a misunderstanding in how scopes function in JavaScript.

Answer №1

This demonstration showcases how you can utilize a URL obtained from an API call to trigger further requests and actions within your code. The possibilities are endless in the .then() block, allowing you to execute any desired function or operation.


Explore the updated CodeSandbox example featuring chained alerts and additional API calls

UPDATE: My answer has been enhanced to illustrate how you can leverage data retrieved from API responses.

https://i.sstatic.net/vnjg6.png


// Utilize the SweetAlert2 component within Modal.vue

<template>
  <div>
    <button @click="swal();">CLICK ME TO LOAD API DATA USING SWEETALERT2</button>
    <div v-if="name != ''">
      <p>Name: {{ name }}</p>
    </div>
    <div v-if="homeworld != ''">
      <p>Homeworld: {{ homeworld }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "",
      homeworld: ""
    };
  },
  methods: {
    swal() {
      let self = this;
      this.$swal
        .fire({
          title: "Click OK to load from: https://swapi.co/api/people/1/",
          showCancelButton: true,
          confirmButtonText: "OK",
          showLoaderOnConfirm: true,
          preConfirm: () => {
            return this.$axios
              .get("https://swapi.co/api/people/1/")
              .then(response => {
                if (response.status != 200) {
                  throw new Error("Something went wrong");
                }
                return response.data;
              })
              .catch(error => {
                this.$swal.showValidationMessage(`Request failed: ${error}`);
              });
          },
          allowOutsideClick: () => !this.$swal.isLoading()
        })
        .then(result => {
          if (result.value) {
            let v = result.value;
            self.name = v.name;
            this.$swal
              .fire({
                title: "Click Ok to redirect to another API call",
                text: `Going to (name:)"${v.name}"'s homeworld URL at: "${
                  v.homeworld
                }"`,
                showCancelButton: true,
                confirmButtonText: "OK",
                showLoaderOnConfirm: true,
                preConfirm: () => {
                  return this.$axios
                    .get(v.homeworld)
                    .then(response => {
                      if (response.status != 200) {
                        throw new Error("Something went wrong");
                      }
                      return response.data;
                    })
                    .catch(error => {
                      this.$swal.showValidationMessage(
                        `Request failed: ${error}`
                      );
                    });
                },
                allowOutsideClick: () => !this.$swal.isLoading()
              })
              .then(res => {
                if (res.value) {
                  self.homeworld = res.value.name;
                  this.$swal.fire({
                    title: "Homeworld",
                    text: JSON.stringify(res.value)
                  });
                }
              });
          }
        });
    }
  }
};
</script>

Answer №2

After reading your comment about the callback being a URL, I realized that axios and sweetalert need the "callback" in JSON format. Here's an example using Laravel. Apologies for any language barriers.

Controller.php

...
if(isAjax){
   return response()->json(['status'=>'info','messages'=>'Winter is coming!','rheader'=>'Warning!']);
}
...

View (Vue with Sweetalert), generic sweetalerts should work as well

...
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.post("{{route('someroute')}}",{id:xid}) //this line passes the id to the route
.then(response => {
  this.$swal(response.data.rheader, ""+response.data.messages+"", response.data.status);
  if(response.data.status=="success"){
    $("#something")).hide();
  }
})
.catch(e => {
  this.$swal("Warning", ""+e.response.data.messages+"", "warning");
});
...

I hope this information proves useful to someone :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring the accuracy of paths in VueJS

I am working on creating specific routes for different users to ensure each user has a tailored experience. For example, if a user is logged in as an admin, they should be directed to '/admin' instead of '/home'. Here's what I&apos ...

What is the best way to remove an item from my online shopping cart using JavaScript?

I am currently developing an online store website. One issue I am facing is deleting items from the cart after a customer completes an order. Below is the array of cart items: const products = [ { id: '0', name: 'Nike Slim Shirt&ap ...

Unusual occurrences when making several ajax requests to a single URL

I've encountered a peculiar scenario while working on a CherryPy server, and I'm seeking assistance in understanding the intricacies behind it. Here's the content of server.py: import cherrypy import os import threading class Root(object): ...

Provide the email address to use on the forum

Is there a way to code an email address in HTML that will be invisible and undetectable by forums? Thank you in advance. I'm looking for a more advanced solution like this one! <h>mariaburkke76</h><h><h><h><h>< ...

Having trouble with creating SQLite tables using JavaScript within a for loop

I have developed a multi-platform app using AngularJS, JavaScript, Phonegap/Cordova, Monaca, and Onsen UI. In order to enable offline usage of the app, I have integrated an SQLite Database to store various data. After conducting some basic tests, I confir ...

Looking for assistance with getting 2 functions to run onLoad using Ajax - currently only 1 is operational

In the coding journey, I first implemented shuffle functions for arrays which was successful. Then, I proceeded to define two global variables that would dictate the random order in which images are displayed on the webpage. The variable picOrder was meant ...

The Vue carousel will continue to autoplay without interruption, even when the flag is changed

I am trying to implement a carousel that autoplays until the user clicks on a dropdown selection, at which point the carousel should stop and navigate to the selected slide. The issue I'm facing is with stopping the autoplay feature. Despite using Vue ...

Excessive alerts being produced within the loop

I am trying to remove a wine from a JSON wine list and I want to display an alert if the wine doesn't exist in the JSON file. However, the alert is popping up for every entry in the list. I am struggling to find a way to use an if statement before pro ...

Incorporate dynamic rules into a CSS stylesheet

I am trying to dynamically add a rule to my CSS for each element. Each rule should have a different background-image and name. However, I seem to be encountering an issue where the dynamically added div is not linking to the dynamically added CSS rule. I&a ...

Nodemailer is having issues, what could be the problem?

I am having an issue with Nodemailer. While it works fine on localhost, it gives me an error message. Can anyone help me identify the problem here? Below is a code snippet in React.js: import React from 'react' import styles from './index.c ...

The Magnificent jQuery Widget Factory's _trigger Instance

When utilizing the _trigger function to initiate events, I often come across a recurring issue that I struggle to fully comprehend. The problem arises when there are multiple instances of my widget on the same page. In such cases, the most recently instan ...

Error: JSON array contains unterminated string literal

Hey there, var favorites = 'Array ( [0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] [1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] [2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] ) '; I've been encountering a syntax error - an untermi ...

Transforming a THREE.js shader into a PIXI.js shader

I am currently exploring the world of PIXI.js and custom Shaders, and I must admit, it's a bit overwhelming for me. I came across a GLSL Shader (created by DonKarlssonSan) that I would like to convert to PIXI.js in order to compare performance. Any as ...

What is the best way to determine if an application has been installed on an Android device while browsing a website?

Let's set the scene: I've got a website that needs to use JavaScript to determine whether my app is already installed on the android device it's currently being used on. If the app is installed, the page will display a link (with a custom ...

"Encountering a 403 error while using the request method in Node.js

app.post("/",function(req,res){ // console.log(req.body.crypto); request("https://apiv2.bitcoinaverage.com/indices/global/ticker/all?crypto=BTC&fiat=USD,EUR",function(error,response,body){ console.error('error:', error ...

Issue with Laravel query not including date filter in where clause

Recently, I created a Laravel query that retrieves all the data without applying the where clause for $startdate. $user->studentGroups()->with([ 'GroupTasks' => function ($queryTwo) use ($startdate) { return $queryTwo-& ...

Exploring elementary Expressjs query concepts

Just getting started with nodejs and feeling a bit confused. I have a form on my website where users can submit information, and I want to display a response message in an HTML element once the form is submitted. I've been using body parser and Jade v ...

validation of dialog forms

Is there a way to trigger the $("#form").validated() function from the ok button in a jquery-ui-dialog? Please note that I would prefer not to use a submit button within the form. ...

What is the best way to display long text in a browser alert without it being cut off?

Seeking to display a large amount of data in an alert box, but only a portion is currently visible. The following text is all that can be seen: ["19467,1496257152583","19227,1496256651094","19469,1496257033968","17285, ...

Retrieve the order in which the class names are displayed within the user interface

In the following code snippet, each div element is assigned a common class name. <div id="category_9" class="list_item" data-item_ids="[38]"</div> <div id="category_2" class="list_item" data-ite ...