I cannot display this API data

I have been stuck with this for over 2 days. please help.

I can view the API data using console.log(data.data) but can’t seem to be able to display it on my html nor loop through it.



fetch("https://travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com/v1/prices/monthly?origin=LHR&destination=DXB&currency=GBP", {
	"method": "GET",
	"headers": {
		"x-access-token": "72891577707fcf74feb69ed1072907cd",
		"x-rapidapi-key": "29c6caa1fcmsh4dd0870566ba44bp141221jsnc1675a6c04bb",
		"x-rapidapi-host": "travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com"
	}
		

})
.then(response => response.json())
.then(data =>{
	console.log(data.data);

	let html = "";
	if(data){
		[data].forEach(data =>{
			html +=`
			
		<div class="item">
			<img src="" alt="">
			<div class="flex-container">
		  	<h1 class="title">${data.data["2021-06"].origin}</h1>
		  	<a class="view-btn" href="#">Read More</a>
			</div>
			<p class="item-data">${null}</p>
	  </div>
			
			`;

			searchResultDiv.innerHTML = html;
		})
	}
})

.catch(err => {
	console.error(err);
});

[off-topic]
Hi there. When you post code in the forum, you need to format it. To do so you can either select all the code and click the </> button, or type 3 backticks ``` on a separate line both before and after the code block.

I have done it for you this time.
[/off-topic]

You are working with an object, with a bunch of properties, whose values are objects:

{
  "2021-06": { origin: "LON", destination: "DXB", price: 270, … },
  "2021-07": { origin: "LON", destination: "DXB", price: 264, … },
  ...
}

This means you can use a reduce statement to iterate over each of the object’s properties, then construct a string of HTML which you can insert into your page.

Here’s a simple demo:

function displayResults(data) {
  const html = Object.keys(data).reduce((acc, key) => {
    acc += `<li>
      <h2>${data[key].origin} to ${data[key].destination}</h2>
      <p>Departure: ${data[key].departure_at}</p>
      <p>Price: ${data[key].price}</p>
    </li>`;

    return acc;
  }, '');

  document.body.innerHTML = `<ul>${html}</ul>`;
}

fetch(
  // eslint-disable-next-line max-len
  'https://travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com/v1/prices/monthly?origin=LHR&destination=DXB&currency=GBP',
  {
    method: 'GET',
    headers: {
      'x-access-token': '72891577707fcf74feb69ed1072907cd',
      'x-rapidapi-key': '29c6caa1fcmsh4dd0870566ba44bp141221jsnc1675a6c04bb',
      'x-rapidapi-host': 'travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com',
    },
  }
)
  .then((response) => response.json())
  .then((result) => {
    displayResults(result.data);
  })
  .catch((err) => {
    console.error(err);
  });

HTH

2 Likes

Hi James,

Thank you so much.

You are a life saver!

does it work in jquery too?

Does what work in jQuery?

Hi, I mean does that way also work when using ajax jquery?

but it’s okay I’ve also managed to use the fetch method like yours. but I’m still confused about how to display the full city name instead of just displaying the iata code.

then how to display the name of the city if by adding an autocomplete like this

https://suggest.travelpayouts.com/uaca/v1/search_terms_forward?&locale=en&service=aviasales_airports&term=Lax

so that it can display the name of the city.

is it possible?

Well, jQuery is just JavaScript, so the question as to whether it works using jQuery is “yes”.

If you post the code you have so far and highlight the bit you are having trouble with, I don’t mind taking a look.

I don’t have the code either.

as you know the travelpayouts API only displays the iata codes from each city and cannot display the city name data.

is it possible to use the data from the autocomplete by entering it or combining it with the script code that you have created.

sorry I forgot I’ve tried before, like this is my code. but my code has a different endpoint.

const settings = {
	"async": true,
	"crossDomain": true,
	"url": "https://travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com/v2/prices/latest?destination=SUB&origin=&period_type=year&one_way=%20false&show_to_affiliates=true&trip_class=0&currency=USD&page=1&sorting=price&limit=8",
	"method": "GET",
	"headers": {
		"x-access-token": "e3f5d349ea54ab0af9049686d7c1520e",
		"x-rapidapi-key": "7553c9c4b0msh01b4944e1049a81p158876jsn340bfdd90264",
		"x-rapidapi-host": "travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com"
	}
};
const matrix = {
	"async": true,
	"crossDomain": true,
	"url": "https://travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com/v2/prices/latest?destination=SUB&origin=&period_type=year&one_way=%20false&show_to_affiliates=true&trip_class=0&currency=USD&page=1&sorting=price&limit=8",
	"method": "GET",
	"headers": {
		"x-access-token": "e3f5d349ea54ab0af9049686d7c1520e",
		"x-rapidapi-key": "7553c9c4b0msh01b4944e1049a81p158876jsn340bfdd90264",
		"x-rapidapi-host": "travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com"
	}
};

function origin(data) {
	asal = data[0].name;
	console.log(asal);
	$.ajax(matrix).done(function(datax) {
		for (var i = 0; i < datax.data.length; i++) {
			ori = datax.data[i].origin;
			document.getElementById('flight').innerHTML = asal;
			var rcp = document.createElement("script");
			auto_url = "https://autocomplete.travelpayouts.com";
			rcp.src = auto_url + "/places2?term=" + ori + "&locale=en_us&types=city%2Cairport&max=1&callback=origin", document.getElementsByTagName("head")[0].appendChild(rcp);
		}
	});
}
$.ajax(settings).done(function(response) {
	var blockbody = '<div class="row no-gutters">';
	for (var i = 0; i < response.data.length; i++) {
		var origin = response.data[i].origin;
		var destination = response.data[i].destination;
		var depart_date = response.data[i].depart_date;
		var return_date = response.data[i].return_date;
		var price = response.data[i].value;
		var found_at = response.data[i].found_at;
		blockbody += "<div class='col-md-6 col-lg-3 ftco-animate fadeInUp ftco-animated'><a href='#' class='block-5' style='background-image:url(https://photo.hotellook.com/static/cities/356x400/" + origin + ".webp)'><div class='text'><span class='price'>$" + price + "</span><h3 class='heading'>Group Tour in " + destination + "</h3><div class='post-meta'><span>" + origin + ", Maldives</span></div><p class='star-rate'><span>Depart: " + depart_date + "</span></p><p class='star-rate'><span>Return: " + return_date + "</span></p></div></a></div>";
	}
	blockbody += '</div>';
	document.getElementById('flights').innerHTML = blockbody;
});

or this one too

const matrix = {
	"async": true,
	"crossDomain": true,
	"url": "https://travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com/v2/prices/latest?destination=SUB&origin=&period_type=year&one_way=%20false&show_to_affiliates=true&trip_class=0&currency=USD&page=1&sorting=price&limit=8",
	"method": "GET",
	"headers": {
		"x-access-token": "e3f5d349ea54ab0af9049686d7c1520e",
		"x-rapidapi-key": "7553c9c4b0msh01b4944e1049a81p158876jsn340bfdd90264",
		"x-rapidapi-host": "travelpayouts-travelpayouts-flight-data-v1.p.rapidapi.com"
	}
};

$.ajax(matrix).done(function(datax) {
    for (var i = 0; i < datax.data.length; i++) {
        var origin = datax.data[i].origin;
        $.ajax({
            url: "https://autocomplete.travelpayouts.com/places2?term=" + origin + "&locale=en_us&types=city%2Cairport&max=1",
            type: 'get',
            dataType: "jsonp",
            success: function(data) {
                for (var i = 0; i < data.length; i++) {
                    asal = data[i].name;
                    console.log(asal);
                    $.ajax(settings).done(function(response) {
                        var blockbody = '<div class="row no-gutters">';
                        for (var i = 0; i < response.data.length; i++) {
                            var origin = response.data[i].origin;
                            blockbody += "<span>" + asal + ",</span>";
                        }
                        blockbody += '</div>';
                        document.getElementById('flights').innerHTML = blockbody;
                    });
                }
            }
        });
    }
});

Hi,

I’ve had a look at your code, but it’s still not clear to me what you are trying to do (or where you are getting stuck).

I’m afraid I don’t have time to work through everything you posted and work out where things are going wrong. What would be better is if you could make a minimal reproducible example which demonstrates the problem you are having.

This explains how:

#1: Probably not the best idea in the world to put your API key on a public forum. Just sayin.

Surely you need to do something to the URL in settings here? Otherwise you’re just calling the generic URL every time this code loops…

Danger Will Robinson - you’re using i for your outer loop’s counter, dont reuse the same variable in the inner loop.

note that this will replace the innerHTML of this element on every iteration of the loop. You may have wanted to append here instead of replace.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.