Search code examples
javascriptdjangohtml-select

Django: Html select with onchange action (without using form) and pure Javascript: redirect with code 200 but page not loaded


I have a select box in my template that reacts on changes with the onchange function that sends the selected value to the Django view. The view gets the required data from the database and should display them.

main.html

{% block content %}
<select class="form-select form-select-lg mb-3 categorySelect select" name="categorySelect"  aria-label="Select category" onchange="getSelectedId(value)">
 <option value="None">Select category</option>
 <option value="all">All</option>
 <option value="cat1">Category 1</option>
 <option value="cat2">Category 2</option>
 </select>
 {% endblock %}

select.js

 function getSelectedId(selectedValue) { 
    const value = selectedValue; 
    const endpoint = "/all/select";
    fetch(endpoint + "?select_id=" + value)
    .then()
   .then(response => { 
   })
   }

views.py

def select(request):
      select_id = request.GET.get("select_id", "None")
      print(select_id)
      if select_id.__contains__('None'):
           return render(request, "home/main.html" )
      elif select_id.__contains__('all'): 
            return redirect(reverse('all:probe_list'))                                     
      elif select_id.__contains__('cat1'):
        selected = "Category 1"
        config = RequestConfig(request)
        resultTable = AllProbesTable(Probe.objects.filter(category = "cat1"))
        config.configure(resultTable)                                           
        return render(request, 'all/selectResults.html', {'table':resultTable, 'selected': selected}) 

I get the correct select_id in the view and the I get a 200 from the redeirect but the page is not changing (similar to This question). I understand that I need to add a reload such as "location.reload()". I added this to the template I am redirecting to but this did not work.

Is there any way to trigger a reload or is there another way to implement a select box with onchange using javascript only?


Solution

  • If the goal is to redirect the user then simply redirect the user, no AJAX needed:

    function getSelectedId(selectedValue) { 
      const value = selectedValue; 
      const endpoint = "/all/select";
      window.location.replace(endpoint + "?select_id=" + value);
    }
    

    Or:

    function getSelectedId(selectedValue) { 
      const value = selectedValue; 
      const endpoint = "/all/select";
      window.location.href = endpoint + "?select_id=" + value;
    }
    

    The former is treated like an HTTP redirect whereas the latter is functionally more similar to a user clicking on a link.