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.


// 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

Initial position of jQuery slider

A while back, I came across some slider code on a website and copied it. Unfortunately, I can't seem to locate the source now. Here is the code snippet: slides.min.jquery.js $(function(){ $('#slides').slides({ preload: true, ...

The system failed to locate the necessary dependency: * firebase within the file path ./src/firebase/firebase.js

Here are the dependencies specified in my package.json file: "dependencies": { "core-js": "^3.6.5", "firebase": "^9.0.0", "vue": "^3.0.0", "vue-router": "^4.0.11" ...

Mongoose is unable to update arrays, so it will simply create a new array

Having trouble updating my collection without any errors. Can someone lend a hand? I've been at this for 3 hours now. const product_id = req.body.cartItems.product_id; const item = cart.cartItems.find(c => c.product_id == product_id); i ...

The Vue-cli webpack development server refuses to overlook certain selected files

I am attempting to exclude all *.html files so that the webpack devserver does not reload when those files change. Here is what my configuration looks like: const path = require('path'); module.exports = { pages: { index: ...

Obtaining response object when encountering 401 error in AngularJS

I am currently working with Angular 1.6.4, Express 4.15.2, and express-session. My goal is to identify whether a user is unauthorized to access a specific route by checking for the existence of the req.session.user parameter. If the user is not authorized, ...

The functionality of jQuery touch events on iOS devices is not functioning properly

I'm encountering issues with jQuery touch events on iOS devices. Here is my current script: $(document).ready(function(){ var iX = 0,iY = 0,fX = 0,fY = 0; document.addEventListener('touchstart', function(e) { ...

Is it possible to directly utilize functions from an imported JavaScript library, such as Change Case, within the template of a Vue component?

After successfully importing and using the Change Case library within the <script></script> element of a Vue component, I now seek to directly utilize the Change Case functions in the template itself. As of now, my understanding is that when d ...

Module for managing optional arguments in Node.js applications

I'm on the hunt for a Node.js module that can effectively manage and assign optional arguments. Let's consider a function signature like this: function foo(desc, opts, cb, extra, writable) { "desc" and "cb" are mandatory, while everything else ...

What are the steps for implementing responsive design animation in my particular scenario?

Can someone please help me with a strange bug in Chrome? I am trying to create a responsive design for my app. The width of the 'item' element should change based on the browser's width. It works fine when the page first loads in Chrome, b ...

Electron: Interactive menu customization

Is there a way in Electron to dynamically enable/disable specific MenuItem in the context menu based on the element that the user right-clicks on? Additionally, I am looking for a method to identify the exact element clicked and pass that information to th ...

Search for data in Mongoose by utilizing a query object that has been obtained from a query string

After extracting and parsing a querystring from a URL, I am able to map it into an object structure like this: { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] } This object is st ...

jQuery - patience is required until all elements have completely faded away

I am facing a unique challenge: I need to trigger an action after two specific elements have been faded out simultaneously. The code snippet for this task is as follows: $("#publish-left, #publish-right, #print-run").fadeOut(function(){ //do something ...

Why isn't changing the property of a Sequelize instance having any effect?

While I've successfully used the standard instance syntax in the past, I'm facing a challenge with updating an instance retrieved from the database in this specific section of my code. ... const userInstance = await db.models.Users.findOne({wher ...

Issues with jQuery functionality occurring when trying to display or hide div contents on dynamically loaded AJAX content

I have encountered an issue while working on a project that involves showing or hiding a div based on the selection of a drop down value. The show/hide functionality works perfectly when implemented on the same page, but it fails when I try to do the same ...

Can you please explain the process of retrieving the value of an item from a drop-down menu using JavaScript?

I am currently developing a basic tax calculator that requires retrieving the value of an element from a drop-down menu (specifically, the chosen state) and then adding the income tax rate for that state to a variable for future calculations. Below is the ...

Choose not to alter the display value during keyup and keydown events, while still triggering the change event

$(function(){ $(".cls_user_details select").keyup(function(){ $(".cls_user_details select").val("Profile"); }) }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="cls_user_setti ...

Achieving functionality with dropdown menus in jQuery

I am facing an issue with a dropdown menu that works perfectly in jsFiddle during testing, but does not function as expected when I run it on my testing server. jsFiddle: http://jsfiddle.net/cyberjo50/39bu8/2/ HTML <!doctype html> <html> < ...

Effectively implementing an event observer for dynamically loaded content

I want to set up an event listener that triggers when any of the Bootstrap 3 accordions within or potentially within "#myDiv" are activated. This snippet works: $('#myDiv').on('shown.bs.collapse', function () { //code here }); Howeve ...

Discovering a specific URL link element within the DOM using webdriver.io

I am currently utilizing webdriver io for conducting tests on a webpage. I am in need of verifying the existence of an element with a specific href on the page. I have attempted to achieve this using the following snippet var client = webdriverio.remote ...

limit stop choice

I'm working on modifying a script to limit the number of selections that can be made. Specifically, I want it to stop allowing selections once the total selected items reach or exceed 4. http://jsfiddle.net/dw6Hf/51/ $(function() { $(".selectabl ...