Better practice to make several ajax requests?

0

I need to clear the following doubt. I want to make 2 ajax requests, the problem is that I make the request 1 (I get a data) and I need to pass that data to the request 2. I have done the following:

  • I create an ajax (jquery) and I get the data
  • Within this ajax I create the following to send the obtained data to the following address
  • ERROR Doing it this way, I get cors error. If I do the ajax on the outside I can not get the data of the request 1

    POSSIBLE SOLUTION When obtaining the data of petition 1, save it in a hidden input and then take it and make the second request

    NOTE I think there should be another more practical and more professional way to carry out this task, any suggestions?

    CODE - If a fetch or other library is best practice, please notify

        $.getJSON("endpoint1", function (data) {
            var datos = data;
            $.ajax(
                {
                    url: "endpoint2",
                    data: { datos: datos },
                    type: "POST",
                    dataType: "json",
                    success: function (cb) {
                        console.log('success')
                    }
                })
        })
    
        
    asked by Alex Hunter 24.09.2018 в 20:48
    source

    1 answer

    1

    Ajax offers the possibility of using callbacks when making a request, example:

    function getUserLocation(callback) {
      $.ajax('https://www.example.com/location.json', callback)
    }
    
    function getCurrentWeather(userLocation, callback) {
      $.ajax('https://www.example.com/weather' + userLocation +  '.json', callback);
    }
    
    getUserLocation(function(user) {
       getCurrentWeather(user, function(weather) {
           console.log("Got weather", weather); 
       });
    });
    

    Source: link

    Here basically what happens is the following: we create two functions, the first getUserLocation is responsible for bringing the data that we need, in the example simply brings the user's location. The second function, getCurrentWeather takes that location as a parameter and makes the second request. At the end once both requests have been made, the last callback will be launched, in the example, it will be printed in console Got weather .

    Greetings!

        
    answered by 24.09.2018 / 21:02
    source