javascriptpythonfetch-api

My div diplays for a second and then disappears


I have this html page that receives html elements got from javascript as shown in the code below. I aim to display the information in a div called 'results'. It displays for a second, and then it disappears as if it's being replaced suddenly.
Why is this happening?
How do I fix it?

const form          = document.getElementById('symptom-form');
const resultDiv     = document.getElementById('result');
const symptomsInput = document.getElementById('symptoms');

form.addEventListener('submit', function(event) {
  event.preventDefault();
  const symptoms = symptomsInput.value.trim();

  // Input validation
  if (!symptoms) {
    resultDiv.innerHTML = '<p style="color: red;">Please enter your symptoms.</p>';
    return;
  }
  resultDiv.innerHTML = '<p>Analyzing symptoms...</p>';
  fetch('http://localhost:5000/diagnose', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({  symptoms: symptoms, email: loggedInUser.email }),
  })
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    resultDiv.style.display= "block";
    displayResults(data, symptoms);
  })
  .catch((error) => {
    console.error('Error:', error);
    resultDiv.innerHTML = '<p style="color: red;">An error occurred while processing your request. Please try again.</p>';
  });        
});

function displayResults(data, symptoms) {
  resultDiv.innerHTML = `
    <h2>Diagnosis Results</h2>
    <p><strong>Symptoms:</strong> ${symptoms}</p>
    <p><strong>Possible Condition:</strong> ${data.diagnosis}</p>
    <p><strong>Recommended Action:</strong> ${data.recommendation}</p>
    <p><strong>Disclaimer:</strong> This is an educational demonstration only.
    Always consult with a qualified healthcare professional for real medical advice.</p>`;

  // Clear the input field for the next entry
  symptomsInput.value = '';
}

Solution

  • The issue occurs because the code that clears the symptomsInput.value is inside the displayResults function. When the input field is cleared, the form gets submitted again, causing the page to refresh. To prevent this, you should clear the input field immediately after the event.preventDefault().

    Here’s the corrected explanation: "The issue arises because the code to clear symptomsInput.value is within the displayResults function. When the input field is cleared, the form is resubmitted, leading to a page refresh. To prevent this, clear the input field right after event.preventDefault()."