I need to clear the following doubt. I want to make 2 ajax requests, the problem is that I make request 1 (I get data) and I need to pass that data to request 2. I have done the following:
- I create an ajax (jquery) and get the data
- Within this ajax I create the following to send the data obtained to the following address
ERROR Doing it this way, I get cors error. If I do the ajax from the outside I can't get the data from request 1
POSSIBLE SOLUTION When obtaining the data from request 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 perform this task, any suggestions?
CODE - If using fetch or another library is better 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')
}
})
})
Ajax offers the possibility of using callbacks when making a request, example:
Source: https://stackoverflow.com/a/36820347/8067370
Basically what happens here is the following: we create two functions, the first
getUserLocation
one is in charge of bringing us the data that we need, in the example it simply brings the user's location. The second functiongetCurrentWeather
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 on the consoleGot weather
.Cheers!