1

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;
});
Enchantres
  • 853
  • 2
  • 9
  • 22

0 Answers0