Holding off $ajax requests until specific code finishes executing

I'm facing an issue with incorporating geolocation data into my $ajax call URL. Currently, both console.log(lat/lon) calls return the initial value of 0, indicating that the geolocation call is too late to provide the updated values. This results in the $ajax calls being made with default latitude and longitude values: "

var lat = 0;
var lon = 0;

console.log(lat);
console.log(lon);

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(pos){
    lat = pos.coords.latitude;
    lon = pos.coords.longitude;
  })
}

function getWeatherData() {
  console.log(lat);
  console.log(lon);
  setTimeout(function(){
    $.ajax({
    url: "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=9011468f93d0dac073b28cda9e83cd01",
    success: function (data) {
      console.log(data);

    },
    error: function () {
      console.log("REKT");
    }
  })
}, 1000);
}

 $(document).ready(function () {
    getWeatherData();
  });

To resolve this, I added an arbitrary timeout function to the $ajax call. However, I am concerned about what would happen if the call takes longer than 1000 or 10000ms. Is there a more elegant solution to ensure that the $ajax call only executes after the geolocation code has finished running?

Answer №1

Adjust the placement of the callback for getCurrentPosition

Unique aspect: The getWeatherData function is now only called if geolocation exists, preventing unnecessary calls.

$(function() { 
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(pos){ 
     lat = pos.coords.latitude; 
     lon = pos.coords.longitude; 
     getWeatherData(); 
   });
  }
});

Additionally, check out this resource: https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only

Answer №2

Invoke your ajax method within the

navigator.geolocation.getCurrentPosition

var lat = 0;
var lon = 0;

function fetchWeatherData(){

   if (navigator.geolocation) {

     navigator.geolocation.getCurrentPosition(function(pos){
        lat = pos.coords.latitude;
        lon = pos.coords.longitude;
    
        $.ajax({
          url: "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon +     "&appid=9011468f93d0dac073b28cda9e83cd01",
          success: function (data) {
            console.log(data);
          },
          error: function () {
            console.log("Error occurred");
          }
        });
    });
   }
 }
                                           

 $(document).ready(function () {
    fetchWeatherData();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You may encounter a problem in Google Chrome

getCurrentPosition() and watchPosition() are no longer functional on insecure origins. Consider transitioning your application to a secure origin like HTTPS

More information available here Google Insecure Origins

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

What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>: export function search(args: SearchInput) { return SomeInterface.performSearch(args) .then(xmlRequest =&g ...

broadcast updated $rootScope

How do I update the $rootScope.$broadcast with a new value? Let's take a look at this code snippet: var test = "fisk"; if(angular.element(this).hasClass('monster')) { var monster_info = angular.element(this).find("img").attr("title"); ...

Aligning the content in the center of a div with inline display

Hi there, I have a quick question for the experts out there. I'm new to all of this so please bear with me :) I'm attempting to center an inline social sharing div on my website, but it's proving to be quite challenging. The div is nested w ...

Material Design Forms in Angular: A Winning Combination

I'm currently working on developing a form using Angular Material. This form allows the user to update their personal information through input fields. I am utilizing "mat-form-field" components for this purpose. However, there are certain fields tha ...

Tips on updating content at a specific time without the need to refresh the page

I'm working on a digital signage script that needs to be time scheduled. I was able to accomplish this using JavaScript and refreshing the page every 15 minutes. However, my question is, how can I track the time and update the content at specific hour ...

Is it possible to create two separate Express sessions simultaneously?

I am encountering an issue with my Passport-using application that has a GraphQL endpoint and a /logout endpoint. Strangely, when I check request.isAuthenticated() inside the GraphQL endpoint, it returns true, but in the /logout endpoint, it returns false. ...

When using AutoComplete in MUI, I encountered an issue while attempting to assign a default value to the checkbox from an API. Instead of achieving the desired result, I received an error stating "(inter

Within this snippet, I am seeking to retrieve a default value from the API to populate a checkbox initially. I have employed the Material-UI Autocomplete component, which includes a defaultValue prop. Despite my efforts to utilize this prop, I am encounter ...

Error: Attempting to access 'map' property of an undefined variable in NEXTJS

I've been struggling to retrieve an image from this API using getStaticProps, but for some reason I can't seem to make it work. In my code snippet, if I add a question mark like this, the console returns 'undefined'. What could be caus ...

Traversing a series of HTML form elements in order to extract their current values and store them in an object

Suppose we have an HTML structure like this: <nav data-filters class=""> <input type="radio" name="type" value="company" checked>Company <input type="radio" name="type" value="product">Product <input type=" ...

"Troubleshooting the inconsistency of GraphQL resolver context functionality between Playground and the client in the official NextJS starter

Currently, I am making adjustments to my NextJS/Apollo application to enable SSG with GraphQL API routes. I have referenced this official NextJS starter example as a foundation for configuring the client. An issue arose in my application which led me to g ...

What is the best way to transform an array of objects into a single string in JavaScript?

After receiving the input from req.body, it looks like this: [ { "Name": "Test_1", "Level 1": "Story_1", "Level 2": "Story_1.1" }, { "Name": & ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Exploring the implementation of constructors and classes in JavaScript

I have a task to create a class named ShoppingCart with specific instructions: The class should have a constructor that initializes the total attribute to zero and creates an empty dictionary attribute called items. There should be a method named add_ite ...

Problems arise when using AngularJS' .run function after navigating to a different page

I have encountered an issue with ngRoute while navigating between pages in my web application. The main login page is called index.html, and the routing is controlled by the main js file. However, I face a problem when trying to use a .run block on a speci ...

Exploring JSON data in React applications

Below is the code I am currently working with: export class Highlights extends React.Component { render() { return ( <div> {JSON.stringify(this.props.highlights_data.data)} </div> ) ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

Incorporating post data into a Partial View

Main objective: My goal is to enable users to click on a specific day on the calendar plugin and have a popup Bootstrap modal display events scheduled for that day. Current Progress: I am currently utilizing a javascript plugin called fullCalendar. With ...

What is the best way to change the class of an input using jQuery when it is not empty?

Utilizing Bootstrap 4. I am working on a feature where I have four text inputs. If any of these inputs contain values, I want to add a specific class to a button. Upon clicking the button, my goal is to clear all input values and remove the aforementione ...

Modify the CSS class dynamically by clicking a button (using class names stored in an array)

How can I dynamically change a CSS class on button press while using an array of class names? When I hard code the classes in a switch statement, everything works fine. However, when trying to pull class names from an array, it jumps to the end of the swit ...

Guide on receiving application/csp-report as json in an express application utilizing bodyParser

I am currently working on creating a middleware that can receive CSP reports from browsers. Browsers send these reports with the Content-Type of application/csp-report, and the data is in JSON format. Right now, I'm using bodyParser.text to handle thi ...