Nested AJAX call yields undefined value

In my Test.vue component, I have a method that is imported into my main.js. I can call its methods like this: this.$refs.test.testMethod().

There is another method in Test.vue called ajaxMethod(), which is defined as follows:

 function ajaxMethod(){
   this.$http.post(url).then(function(res){ return "hi from test"})
 }

When I make an AJAX call from my main method (in main.js) like this:

this.$http.post(url).then(function(response){
let a = this.$refs.test.ajaxMethod()
console.log(a) //a is undefined
})"

I attempted to set the value of a variable in Test.vue and then access it from main.js like so:

//in Test.vue
data:{
  variable:""
}
methods:{
function ajaxMethod(){
   this.$http.post(url).then(function(res){ 
      this.variable="hi from test"
   })
}
}

//in main.js
this.$http.post(url).then(function(response){
   this.$refs.test.ajaxMethod()
    console.log(this.$refs.test.variable) //when i call that function first time result is empty string and when i call it second time result is 'hi from test'
})"

The expected outcome of the ajaxMethod() call is 'hi from test' instead of undefined

EDIT

To resolve this issue, I found a workaround using the following code:

 a.then(function(val){console.log(val)})

It seems that using the value in a promise was necessary, but I'm curious if there is a more conventional solution?

Answer №1

It seems like you forgot to return anything from your ajaxMethod function. Remember, it's important not to tightly couple your components together. Take caution when dealing with synchronous and asynchronous code. The post method actually returns a promise, not the value itself. You can access the value within the callback function.

function ajaxMethod(){
   return this.$http.post(url);
}

Make sure to return the promise:

this.$refs.test.ajaxMethod().then(function(res){
    console.log(res)
})

Then fetch the value. Consider using events instead of direct communication between child and parent components. It helps maintain cleaner architecture.

Edit for clarity: I suggest using events for communication between components rather than the current approach.

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

Vue.js problem with conditional rendering using v-if

I'm struggling to grasp the concept behind how v-if functions. My goal is to dynamically hide buttons in the navigation bar based on the user's authentication status and current page. Specifically, I want the "My Account" button to be displayed w ...

Combining Multiple Arrays into a Single Array

Is there a way to combine this merge operation that creates one array using forEach into a single array at the end? affProd.pipe(mergeMap( event1 => { return fireProd.pipe( map(event2 => { const fi ...

Framer Motion causes a crash in a Next.js application with the error message: "Unable to find named export 'useId'"

I am encountering an error in my Next.js app that I can't seem to trace back to its source. Strangely, the code triggering the error is not something I wrote myself. error - file:///Users/cheq/Desktop/cheqo/node_modules/framer-motion/dist/es/component ...

Angular and Express: Automatically redirecting to the previous page after user login

A question similar in nature can be found here, although not directly relevant to my situation. Within my Single Page Application, I am implementing PassportJS for user authentication. There are multiple routes that necessitate user login. The routing is ...

I would appreciate it if someone could clarify how the rendering process occurs in React in this specific scenario

let visitor = 0; function Mug({name}) { visitor = visitor + 1; console.log(name, visitor); return <h2>Coffee mug for visitor #{visitor}</h2>; } return ( <> <Mug name={"A"}/> <Mug name={"B&qu ...

Nested array in jQuery

Can someone verify the correctness of this array within an array declaration? If it is correct, can someone suggest how I can display or at least alert all the contents in chkArray? var chkArray = { tv_type[],screen_size[],connectivity[],features[]}; va ...

Display or conceal various objects using a single button in HTML

I've been working on creating a chatbot widget for my website, but I've run into an issue. The "Chat with us" button only shows the bot and not the close button as well. Here's what I've attempted: <input id="chat" type="button" on ...

The event for 'deviceready' in Cordova is not getting triggered when placed inside the angular .run block

Recently, I've been facing difficulties in getting 'deviceready' to register within AngularJS. It was functioning properly earlier, so I'm puzzled about what might have altered. If I trigger 'deviceready' from a global addEve ...

WebGL Error: An invalid operation occurred while trying to use the uniformMatrix4fv function. The error code [WebGL-00000A18072FEA00

Currently, I am working on an app that showcases 360° images and I rely on the BabylonJS library for this feature. The navigation bar helps me switch between different 360 locations within the application. However, whenever I try to change the 360 image ...

TypeScript encountered an unexpected { token, causing a SyntaxError

Despite multiple attempts, I can't seem to successfully run my program using the command "node main.js" as it keeps showing the error message "SyntaxError: Unexpected token {" D:\Visual Studio Code Projects\ts-hello>node main.js D:&bsol ...

Apply a specific class using JavaScript/jQuery when a user selects a specific timezone from the user interface

Currently, I am coding in HTML with the code below extracted from this website link. The listings under timezone ET are all correct as they align with the accurate dates; however, for other timezones (PT, MT, CT, AT, NT) some shows seem to be on incorrect ...

Having trouble with $.post request to a different domain in a node.js/express app running on port 8081

Whenever I try to use $.post, I keep getting the error message POST https://thewebsite.com 400 (Bad Request). Here is the code snippet that's causing the issue: $.post("https://website.com/blabla", { domain: "infoinfo.com", room: "someInfo", ap ...

Is there a way to track dynamic changes in window dimensions within Vue?

Working on my Vue mobile web app, I encountered an issue with hiding the footer when the soft keyboard appears. I've created a function to determine the window height-to-width ratio... showFooter(){ return h / w > 1.2 || h > 560; } ...and ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

Learn how to generate a table directly from code instead of relying on a .json file

I need help modifying this code snippet that currently reads JSON data from a file. I have generated the JSON data from my database and would like to update the code to read it directly instead of from a file. You can refer to how the JSON is being accesse ...

Parallel ajax function

After creating a form for registering new accounts, I wanted to ensure that the chosen email is available by checking it against a webservice. However, this process takes a few seconds. Let's take a look at the method used: function validateEmail(ema ...

React state object iteration doesn't produce any visible output

Trying to dynamically showcase checkboxes with starting values from the state using Material-UI for UI components. tagState: { All: true, Pizza: false, Breakfast: false, Chicken: false } Utilized Object entries and forEach to generate checkbox ...

Having trouble adding HTML content to a parent div using jQuery and BackboneJS?

Utilizing Backbone Marionette to create a series of views, I am now faced with the task of making an AJAX call to my backend. In order to provide visual feedback to the user indicating that an action is being performed, I decided to integrate a spinner int ...

Submitting form data to PHP without refreshing the page

I've been attempting to send form data, specifically an array, to a PHP file without having the page refresh. I've implemented AJAX for this purpose but it doesn't appear to be working as intended. Below you'll find the syntax of the fo ...

Modifying and replacing content in a local file using JavaScript

I have a file located in a directory called testfolder on my local disk. The contents of the file are as follows: Apples are red. <colour = red/> latitude 13.124165 Would it be possible to retrieve the content of this file, store it in a variable, ...