Issue with JavaScript fetch and Airtable integration
I’m trying to retrieve survey data from Airtable and display it on my webpage, but I’m running into problems. The fetch request seems to work and I can see the data in the console, but my DOM elements aren’t getting updated with the retrieved information.
I think the problem is that my variables aren’t being properly assigned with the data from Airtable. When I try to display the content, nothing shows up on the screen even though the API call appears successful.
Here’s what I’m working with:
(function() {
window.addEventListener('load', function() {
document.getElementById('continue').addEventListener('click', function() {
window.location.href = 'survey2.html';
})
let quest1 = document.getElementById('question1');
let quest2 = document.getElementById('question2');
let quest3 = document.getElementById('question3');
let quest4 = document.getElementById('question4');
let quest5 = document.getElementById('question5');
let surveyId = 1;
let fetchSurveyData = function() {
fetch('https://api.airtable.com/v0/app123ABC/Survey', {
method: 'GET',
headers: {
'Authorization': 'Bearer key123XYZ'
}
})
.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;
quest1 = q1_data;
quest2 = q2_data;
quest3 = q3_data;
quest4 = q4_data;
quest5 = q5_data;
console.log(quest1);
}
}
})
}
fetchSurveyData();
function displayQuestion() {
let paragraph = document.createElement('p');
paragraph.innerHTML = quest1;
document.getElementById('question1').appendChild(paragraph);
}
document.getElementById('question1').innerHTML = displayQuestion()
})
})();
Any ideas why the variables aren’t getting populated correctly?