Issue with Airtable API data retrieval
I’m trying to retrieve quiz questions from an Airtable database and display them on my webpage, but my variables don’t seem to be getting populated with the data from the API response.
The problem is that when I fetch the data from Airtable, the variables I’m trying to fill remain empty. I think there might be an issue with how I’m assigning the values or maybe with the scope of my variables.
Here’s the code I’m working with:
(function() {
window.addEventListener('load', function() {
document.getElementById('continue').addEventListener('click', function() {
window.location.href = 'survey2.html';
});
let q1 = document.getElementById('question1');
let q2 = document.getElementById('question2');
let q3 = document.getElementById('question3');
let q4 = document.getElementById('question4');
let q5 = document.getElementById('question5');
let surveyId = 1;
let fetchQuestions = function() {
fetch('https://api.airtable.com/v0/appXYZ123/Questions', {
method: 'GET',
headers: {
'Authorization': 'Bearer keyABC123'
}
})
.then(response => response.json())
.then(data => {
console.log(data);
for(let i = 0; i < data.records.length; i++) {
let record = data.records[i];
if(surveyId === record.fields.survey_id) {
let q1_data = record.fields.Question1;
let q2_data = record.fields.Question2;
let q3_data = record.fields.Question3;
let q4_data = record.fields.Question4;
let q5_data = record.fields.Question5;
q1 = q1_data;
q2 = q2_data;
q3 = q3_data;
q4 = q4_data;
q5 = q5_data;
console.log(q1);
}
}
});
};
fetchQuestions();
function displayQuestion() {
let paragraph = document.createElement('p');
paragraph.innerHTML = q1;
document.getElementById('question1').appendChild(paragraph);
}
document.getElementById('question1').innerHTML = displayQuestion();
});
})();
Can anyone help me figure out why my questions aren’t showing up on the page?