Using Axios to Send a JSON Object with Nested Properties

Utilizing the Axios Http Client on my website poses a challenge when it comes to obtaining the user's location through the browser's geolocation feature. Once the location is acquired, I aim to send this data along with other information. To accomplish this, I have constructed a data object structured as follows:

navigator.geolocation.getCurrentPosition(
  function(position) { 
    var data = {
      id: 1,
      user:'me',
      location: position
    };
  })
;

Subsequently, attempting to transmit the data via Axios yields a puzzling outcome:

axios.put('/my-endpoint', data, options)
    .then(function(res) {
      console.log('success');
      console.log(res);
    })
;    

Although I receive a positive response from the request, upon inspecting the logs, an anomaly surfaces - the location property appears as an empty object. This discrepancy becomes evident especially when comparing the browser's logged output which displays correct values for location, contrary to what Fiddler reveals where it is empty during transmission. How is this possible?

This discrepancy leads me to believe there might be a particular configuration or step required to facilitate sending nested JavaScript objects across networks, yet nothing stands out. What could I potentially be overlooking? For demonstration purposes, I've provided a simple JSFiddle showcasing the issue here.

Answer №1

It appears that the variable data is not accessible when attempting to send it. In the given example, data is a local variable within a closure, causing it to be destroyed once the callback is finished. To resolve this issue, you should declare data outside of the function so that axios can access it. You can still modify its value inside the callback, but it must be declared beforehand.

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

Tips for creating a wavy surface on a cylinder using three.js (with images)

I've been working on giving my cylinder geometry a wavy surface, aiming for a look like this: https://i.sstatic.net/aCaV7.png However, after implementing the following code, it ended up looking quite distorted as shown in these images: https://i.ssta ...

Could a single JSON request bring back multiple responses?

How can I structure JSON with a single callback containing multiple objects? I am trying to return 3 values in this example but the calclickM.php file is not working correctly. <?php $choice = (isset($_POST['choice'])) ? date("Y-m-d", ...

Rubaxa's sorting feature conceals floating entities but not the real rows

I have implemented the Sortable plugin by Rubaxa to rearrange rows in a Bootstrap table. Each row in the table contains Bootstrap inputs within its cells. Although the rows can be sorted smoothly, the "ghost" image that appears does not include the input ...

C# - Techniques for Extracting a Single Specific Item from a JSON Response obtained from an API

Currently, I am exploring how to send an image using C# to my Custom Vision Prediction API. This is a new experience for me as I am still learning C#. I encountered some challenges while trying to follow the tutorial provided on the Microsoft Azure website ...

Exploring the concept of using variables and understanding variable scope in AJAX and JavaScript

Struggling with using variables in AJAX. Attempting to have var x store data from var data but it keeps showing as undefined in the console log. Any tips on how to fix this issue? EDIT: The variable x needs to be accessed later in the code, not just for ...

Declaring an object in the form of a function

I need some assistance with calling a method that is declared like an object in the following code. What approach should I take to call the function properly? var draw = function() { anotherFunction(); } draw(); Upon execution, an error stating "Typ ...

Methods for refreshing a child component when new elements are added to a data array

One of my vue.js child components contains a data array named messages. I am looking for a way to refresh the DOM when new elements are inserted into the array. Below is a simplified version of the code snippet: <template> <q-item v-for="(msg, ...

How can I make a dropdown menu appear when I select a checkbox?

Is it possible to have a dropdown menu with changing options appear when I click on a checkbox using HTML and JavaScript? I have experimented with some code snippets in JavaScript as a beginner, but I am unsure if they are needed here. Is there an altern ...

Is there a way to create a dynamic gallery using Magnific Popup that showcases both images and an iframe video together?

One way I am utilizing magnific popup is to set up an image gallery using the code snippet below: $('.main-content').magnificPopup({ delegate: '.gallery', // selecting child items to open in pop-up when clicked type: 'image&ap ...

The Javascript function is designed to function exclusively with onclick events or setTimeout functions

I am currently working on a website that I want to be responsive to the window size. However, I am facing an issue with vertical alignment. I have created a jQuery function to handle this, and it works well for divs with images but not so well for a div wi ...

PHP - Offline/Online Status Polling Protocol Guide for Beginners

I am in search of a solution to track the online and offline status of users on my website. My site is a single page with no clickable links, so users may leave their tabs open for long periods without interaction. It is not essential to pinpoint the exact ...

Eliminating replicated vertices in a Three.js geometry model

I'm struggling with removing duplicate vertices from a SphereGeomerty. I need to eliminate the seam on one side of the geometry as it doesn't align properly when updating the vertex positions. The issue arises when attempting to create a new geo ...

Angular Universal causing issues with updating the DOM component

@Component({ selector: 'mh-feature-popup', template: ` <div class="full"> <div> <div class="container-fluid" [@featurepop]="state"> <div class="row"> <div class="col-xs-12 col-md-4 col-md-offse ...

The behavior of input types disabled and readonly varies when combined with a hyperlink (a href

In the code snippet below, I am trying to disable and enable a calendar clickable icon. <p> <label> <input type="text" name="date18" id="date18" value="01/01/2012" style="width:75px;" disabled/> </label> ...

Validating JSON data with AJV (Another JSON Validator)

Looking for assistance on JSON validation. let schema = { "type": "object", "required": ["name", "profession"], "properties": { "name": { "type": "string" }, "profession": { "oneOf": [ { "$ref": "#/d ...

How can I organize the output from JQ when using the Bash shell?

I am looking to develop an automated script that can extract specific values from JSON data and display them (in this case, in a terminal). Below is the complex code I have written: for ((i = 0 ; i < 34 ; i++)); do echo " \ $(curl ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

Sending data as a string in an AJAX request

I have been struggling with this coffeescript function that controls dynamic select boxes. I am trying to pass the content of "modelsSelect" to another script, but for some reason, it's not working as intended. customScript.coffee dynamicSelection = ...

Determine if an object has been submitted in a MEAN / AngularJS application

I am working with an AngularJS frontend and using Express, Node, and MongoDB on the backend. My current setup is as follows: // my data to push to the server $scope.things = [{title:"title", other properties}, {title:"title", other properties}, {titl ...

Injecting a full browser-screen DIV into the body of the webpage

Recently, I was tasked with developing a script that could be utilized on any website. As a test, I decided to use the Google search results page. My goal is simple - to have a full-screen semi-transparent div displayed on any site for cookie notification ...