Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
How to solve ajax call delay?

I have an input field named location. When clicked on the search button, I want to take the input from the location field and using ajax to get the location details. The function getLocationData() returns the needed info, but the line

let locationData = getLocationsData();

in the click button function returns null. In the console, firstly, the console.log() from the click button function is called and then the console.log() from the getLocationData(). Can someone explain why it is called first? How can I solve this issue?

const baseUrl = 'https://booking-com.p.rapidapi.com/v1/hotels/';
var locale = "en-gb";

function getLocationData(){
    var destination = {};
    var location = $('#location').val();
    var route = "";
    if(location != null || location != ""){
        route = `locations?locale=${locale}&name=${location}`;
    }
    console.log(`${baseUrl}${route}`);
    $.ajax({
        method: "GET",
        url: `${baseUrl}${route}`,
        headers:{
            'x-rapidapi-host': 'booking-com.p.rapidapi.com',
            'x-rapidapi-key': 'api-key'
        }
    })
    .done(response => {
        if(response[0]["dest_type"] != "hotel"){
            destination = {
                "label":response[0]["label"],
                "dest_id": response[0]["dest_id"],
                "dest_type": response[0]["dest_type"]
            };
        }
        console.log("getLocationData()", destination);
        return destination;
    })
    .fail(response => {
        console.log("ajax failed",response);
    });
}


$('#search-hotels').click(function () {
    let dateRange = getDateRangeObject();
    let checkin = dateRange['checkin'];
    let checkout = dateRange['checkout'];
    let isCheckinInvalid = moment(checkin).isBefore(moment(new Date()).format('YYYY-MM-DD'));
    let isCheckoutInvalid = moment(checkout).isBefore(moment(new Date()).add(1, 'days').format('YYYY-MM-DD'));

    let adults = $('#adults').val();
    let rooms = $('#rooms').val();
    let isAdultsAndRoomValid = adults >= 1 && rooms >= 1;
    let locationData = getLocationsData();
    
    let destination = {...locationData};
    console.log("click button function",destination);

    if (location != "" && !isCheckinInvalid && !isCheckoutInvalid && isAdultsAndRoomValid) {
        window.location.href = `hotels.html?location=${location}&checkin=${checkin}&checkout=${checkout}&adults=${adults}&rooms=${rooms}`;
    }

    return false;
});
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda