Tips for sending data from Ajax to another function

Can you assist me in understanding how to retrieve values from an ajax function and then use them in a different function? Here is an example:

 function getlanlon(){
                  $.ajax({
                  type: "GET",
                  url: "{{URL::to('/')}}/getlatlng",
                  //data: {value: 0},
                  //async: true,
                  success: function(result){

                   console.log(result)
                  }

              }, "json");
          };

Now, the challenge lies in calling the "result" from the above function into the following function. However, it seems to not be working as expected, with the console log consistently showing undefined.

          map.on('load', function () {

             latlon = getlanlon()
               console.log(latlon)


}

Answer №1

If you're looking to retrieve data asynchronously, you have a few options such as using a callback function, promise, or deferred object:

function fetchDataWithCallback(callback){
    $.ajax({
        type: "GET",
        url: "{{URL::to('/')}}/getData",
        success: function(result){
            if(callback){
                callback(result);
            }
            console.log(result)
        }

    }, "json");
};

map.on('load', function () {

    fetchDataWithCallback(function(data){
        console.log(data)    
    })
}

Another approach is to use a Deferred object:

function fetchDataWithDeferred(){
    var deferred = $.Deferred();
    
    $.ajax({
        type: "GET",
        url: "{{URL::to('/')}}/getData",
        success: function(result){
            deferred.resolve(result);
            console.log(result)
        }

    }, "json");
    
    return deferred;
};

map.on('load', function () {
    
    fetchDataWithDeferred()
        .then(function(data){
            console.log(data);
        })
    })
}

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

Creating middleware to intercept responses for all AJAX requests

I'm working on creating a middleware that will manage all web user responses. Here's what I have so far: function ajaxResponseMiddleware(req, res, next) { var code = res.locals._code || 200; var data = res.locals._response; res.json(co ...

Tips for combining or adding duplicated values in a Javascript array

I am facing a problem with an array object that looks like this: [ {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"origin ...

I am encountering errors when running NPM start

After setting up my webpack, I encountered an error in the terminal when attempting to run the code npm start. The specific error message was related to a module not being found. Can someone please assist me with resolving this issue? > <a href="/c ...

Data from AngularFire not displaying in my list application

While going through tutorials on the Angular website, I encountered a roadblock while attempting to create a list that utilizes Firebase for data storage. Strangely, everything seems to be functional on the Angular site, but clicking on the "Edit Me" link ...

What could be causing the issue with my validation for alphabetical input?

I am currently working on a registration form that only accepts alphabetical input. However, I am facing an issue where my error message appears regardless of whether I input an alphabetical or special character. According to my understanding, the code sho ...

retrieve information using ajax

While utilizing Google Translate on a webpage where I am using $.ajax to retrieve data, I have encountered an issue. The translation does not work properly for the text fetched through $.ajax. When checking the page source in the browser, no text is displa ...

When attempting to add or store data in MongoDB, it triggers a 500 server error

Greetings, I am currently working on developing a CRUD app using the MEAN stack. The Express application loads successfully and retrieves the "contactlist" collection from the database. However, when attempting to make a POST request to "/api/contacts", an ...

What is the process for deleting a token from local storage and displaying the logout page in Next JS?

I developed a Next.js web application and am looking to display a logout page when the token expires, while also removing the expired token from local storage. How can I ensure that this functionality works no matter which page the user visits within the a ...

Why does JavaScript often return the constructor of an object instead of false?

Seeking assistance in resolving issues with the functionality of my script. function CatFactory(cat) // Cat constructor { for (y in cats) { if (cats[y].color == cat.color) {return false;} // return false if already in the array ...

What steps should I take to resolve the issue where Angular project error states that the data path "/polyfills" must be a string?

I am struggling with deploying my Angular app to Firebase and/or running it successfully locally using NodeJS version 18. To access the package.json and source code, you can click on this link: https://github.com/anshumankmr/jovian-genai-hackathon/blob/mas ...

JSON appears to be failing to be identified

I am encountering difficulties in getting my JSON data to display correctly on my web page. Even though I have validated the JSON returned from the server and confirmed its correctness, my javascript function seems unable to process it as intended. Here is ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

One function in Typescript lodash is missing a default export

Is there a way to import just one function from lodash? I attempted it like this: import get from 'lodash/get'; Even after installing both lodash and @types/lodash, I encountered the following error message: @types/lodash/get/index"' ha ...

creating a div with the help of Ajax

I developed an ajax function that retrieves a list of products. I want to showcase these products in a specific div, meaning that I need to duplicate this div for each product and show the product name within a paragraph tag. The code below was my attempt, ...

Steps to indicate a selected check column in a grid

I am working with a grid that has a check column, and I need to programmatically mark the checkbox. This is how the check column is coded: columns: { items:[ { itemId: 'checkColumn', xtype: 'selectallche ...

The issue with jQuery trigger not passing the value of a radio button has been

I have implemented a radio button (Yes, No) and an input text box on my form. If the user selects 'No', the input field is disabled and jQuery triggers a change event for AJAX form submission. $('#form-id').change(function(){ .... }); ...

HTML table row content should be aligned to the left side

I am attempting to align the data in the 'Address' column without any margin. I want it to start from the left since it's overflowing. You can find the HTML, CSS, and JS code here Even though I tried using <td align="left">..</td& ...

Updating a singular value in an array using jQuery/JavaScript

Within a Javascript function, I have created an array called HM_Array1. The contents of the array are listed below: HM_Array1 = [[,11,147,,,,,,,1,1,0,0,0,1,"csiSetBorder(this)","null",,,true,["&nbsp;&nbsp;&nbsp;Accoun&nbsp;&nbsp;& ...

guide on updating JQuery string with JavaScript to incorporate new parameters

Similar Question: How to replace only one parameter or fast with Jquery on Jquery String The website has a query string as follows: http://www.nonloso.html/?nome1=pollo&cognome1=chicken&nome2=a&cognome2=b&nome3=c&cognome3=d This ...

"Simply tap on an element that has been dynamically inserted into the

Many individuals are familiar with how to attach a "click" event to an element that is dynamically added using the following syntax: $('#main').on('click','.link',function(){ //some code here }); In this example, .link repr ...