Prevent page reloads w/ Ajax/JS (no jQuery): use event.preventDefault()

Problem

I’m trying to avoid page reloading when clicking a button, which prints some text in a textarea, in the home.html (index.html > login.html > home.html) page. This page contains a combobox, a textarea, and a button. The text is retrieved from views.py using a condition.

I want to use Fetch in pure Javascript to prevent page reloading, instead of Ajax. However, I also need to be able to manage many comboboxes without splitting the code too much in the js file or js tag.

Is there a way to do this?

Yes, you can use the Fetch API in pure JavaScript to prevent page reloading when clicking a button. Here’s an example of how you can achieve this:

In your home.html file, you can add an event listener to the button that will make a fetch request to views.py and update the textarea with the response. Here’s an example code snippet:

<!DOCTYPE html>
<html>
<head>
  <title>Home</title>
</head>
<body>
  <select id="combobox">
    <!-- options for combobox -->
  </select>
  
  <textarea id="result" rows="5" cols="30"></textarea>
  
  <button id="submitButton">Submit</button>

  <script>
    document.getElementById("submitButton").addEventListener("click", function() {
      var comboboxValue = document.getElementById("combobox").value;
      
      fetch("/path/to/views.py?comboboxValue=" + comboboxValue)
        .then(response => response.text())
        .then(data => {
          document.getElementById("result").value = data;
        })
        .catch(error => {
          console.error("Error:", error);
        });
    });
  </script>
</body>
</html>

In your views.py file, you can retrieve the comboboxValue from the request parameters and return the desired text based on the condition. Here’s an example code snippet:

def your_view(request):
    combobox_value = request.GET.get("comboboxValue")
    
    # Perform your logic based on the combobox value
    if combobox_value == "option1":
        result = "Text for option 1"
    elif combobox_value == "option2":
        result = "Text for option 2"
    else:
        result = "Default text"
    
    return HttpResponse(result)

Make sure to replace /path/to/views.py with the actual URL that points to your views.py file.

This way, when the button is clicked, the fetch request is made to views.py and the response is used to update the textarea without reloading the page.