Guide 3.3: Real Projects

Fetch JAMB Subjects

Now that our home screen UI is built, it's time to bring it to life using JavaScript. We need to query SdashAPI for the list of available subjects and dynamically populate our HTML dropdown.

API Configuration

3.3.1

Open your app.js file. First, let's declare our API key and the base URL as constants at the top of the file so we can reuse them.

const API_KEY = 'YOUR_ACCESS_TOKEN'; // Replace with your real token!
const API_BASE = 'https://sdashapi.com/api/v1';

// DOM Elements
const subjectSelect = document.getElementById('subjectSelect');
const startBtn = document.getElementById('startBtn');

The Fetch Function

3.3.2

Let's create an asynchronous function that calls the /subjects endpoint and iterates over the returned JSON array to create <option> elements.

async function loadSubjects() {
  try {
    const response = await fetch(`${API_BASE}/subjects`, {
      headers: { 'AccessToken': API_KEY }
    });
    
    if (!response.ok) throw new Error('Failed to load subjects');
    
    const data = await response.json();
    
    // Clear the "Loading..." placeholder
    subjectSelect.innerHTML = '<option value="">-- Select a Subject --</option>';
    
    // Populate the dropdown
    data.data.forEach(subject => {
      const option = document.createElement('option');
      option.value = subject.slug; // We use the slug for API calls!
      option.textContent = subject.name;
      subjectSelect.appendChild(option);
    });
    
    // Enable the dropdown now that data is loaded
    subjectSelect.disabled = false;
    
  } catch (error) {
    subjectSelect.innerHTML = '<option value="">Error loading subjects</option>';
    console.error(error);
  }
}

// Call the function immediately when the page loads
loadSubjects();

Enabling the Start Button

3.3.3

We shouldn't allow the user to click "Start Exam" if they haven't actually selected a subject. Let's add an event listener to the dropdown that enables the button only when a valid subject is chosen.

subjectSelect.addEventListener('change', (e) => {
  if (e.target.value !== "") {
    startBtn.disabled = false; // Valid subject selected
  } else {
    startBtn.disabled = true; // Returned to default option
  }
});

UI is ready!

Next, we will write the logic that runs when the user clicks the Start button.

Next Guide: Fetch Questions →
Avatar

How can we help?

We reply immediately

Hello! 👋 How can we help you today?