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

execute the function based on the given ID

I've been attempting to dynamically add content using a function. My goal is for the content with the same anchor ID as the clicked anchor to be added, but it seems like nothing is happening. Is there a more effective approach to achieve this? $(&a ...

Developing a music playlist using javascript/angular (replicating array elements while linking nested objects)

I am currently working on creating a playlist for a music player within an Angular app that includes a shuffle feature. The actual shuffle function is not the issue, as I am utilizing the Fisher Yates Shuffle method and it is functioning correctly. When th ...

Angular filter within a nested ng-repeat loop

I've encountered an issue with nested filtering in Angular, where two filters are dependent on each other. What I'm trying to achieve is the following: <div ng-repeat="g in groups | filter:groupFilter"> ... <tr ng-repeat="c in g.co ...

React-Leaflet continuously updates the map with the "MouseMove" event

I'm looking to implement a feature in my React app that displays the geographic coordinates as the mouse moves. However, I've noticed that using "Mousemove" causes the map to be continually redrawn with all objects each time, resulting in poor pe ...

Restricting the type of user input in HTML forms

Requirements: Input must be a whole number between 2 and 99, inclusive. Current Solution: <input required type="number" min="2" max="99" oninput="this.value = Math.abs(this.value)" maxLength="2" matInp ...

Switching the default browser for npm live-server

When I use the npm live-server package to preview my website as it changes, it keeps opening in Edge even though Chrome is set as my default browser on my system. I attempted to use the command suggested on the npm website: live-server --browser=chrome H ...

Need help triggering Ajax code upon clicking a link?

Can someone help me find the issue with my script? Below is the code snippet: <script> $(".icross").click(function(e){ e.preventDefault(); var obj = $(this); $.ajax({ type: "GET", url: "supprimer.php", data: 'id=&a ...

Showing chosen checkbox information using jQuery ajax

When a user enters more than 3 characters into a text box for live search, results are displayed from the database via an AJAX response as checkboxes with names. I want selected checkboxes to display in a separate div below so users can search multiple dat ...

I am looking to update the appearance of a button dynamically in Vue.js based on changes to an

Is there a way to toggle a visible button when the array changes? I'm having trouble implementing this. What is the most effective method? Check out my example below: https://codesandbox.io/s/relaxed-poincare-vv6xh?file=/src/components/HelloWorld.vu ...

Saving data to a database using jQuery Ajax when multiple checkboxes are checked

Looking for a solution to store checkbox values into a database using jQuery Ajax to PHP. To see a live demo, click here. The image above illustrates that upon checking certain checkboxes and clicking Update, the checkbox values along with their IDs will ...

Utilizing setColumns() function within Google Charts for JSON data tables

Is there a feature in the Google Charts API that functions similar to setColumns() for working with JSON data? I'm aiming to reduce PHP calls by consolidating my data into a single array and then specifying which columns Google Charts should utilize. ...

Redux: The action was effectively triggered, but the state remained unformed

I'm currently working on a project to familiarize myself with Redux. I am using the Redux DevTools to monitor my two states: lists and todos. However, I am running into an issue where only todos are being displayed, despite trying various troubleshoot ...

Automatically populate editbox in Magento upon exiting

I'm facing a seemingly simple question but struggling to find a solution. I have a frontend form with various input boxes where users can enter a blog URL. Upon exiting the box, I want to: Extract and retrieve tags related to the OpenGraph protocol ...

Upon migrating from Vue CLI 2 to 3, an error is thrown stating: "Cannot locate element: #app" and an empty body is

Currently, I am in the process of transitioning my VueJS project from VueCLI 2 to version 3. After moving all the necessary files to the src folder, I attempted to view it in the browser by running npm run serve. However, I encountered a problem where the ...

Having trouble with shipit.js deployment: Error encountered - git checkout undefined

I have been using shipit.js to deploy my nodejs application on an Ubuntu 16.04 server successfully. However, I recently encountered the following error: ./node_modules/shipit-cli/bin/shipit production deploy start Running 'deploy:init' task... ...

Triggering a new window on button click with Vue and Nuxt

Having an issue with a button click event in Vue that opens a PDF using window.open(). It's working well on all browsers except for Safari on MAC. Any ideas what could be causing this? Should I pass $event to the method? <div class="button-do ...

The styled-components seem to be having trouble injecting the necessary CSS to handle all the various props

I am curious to understand the potential reasons for styled-components not injecting all the necessary CSS into a page's header. In an existing project, I have defined a simple button like this: const Button = styled.button` background-color: ...

When I try to import script files into my ASP.NET page, Intellisense displays the methods accurately. However, when I attempt to call one of them, an

I added a function to an existing .js file (I tried two different files) in order to make the method accessible in multiple locations without having to repeat the code. I also created a simple function just to confirm that my function wasn't causing a ...

What is the origin of this mysterious error?

I'm working on a function to format various types of variables and utilize a toString() method. It's handling complex objects, arrays, and circular references flawlessly. However, when testing it on a jQuery object using format($("body")) with l ...

TypeScript does not recognize the $.ajax function

Looking for help with this code snippet: $.ajax({ url: modal.href, dataType: 'json', type: 'POST', data: modal.$form.serializeArray() }) .done(onSubmitDone) .fail(onSubmitFail); ...