Using Javascript and AJAX in the Fetch()API method: returns no values as a response

Please be patient with me, … what I have found online about Django Template Partials indicates that forms will play a part in utilizing an HTML fragment, however, my app isn’t exactly making use of any forms. I’d appreciate your comments ??

After reading the Django Tutorial to get a sense of how a database can be accessed through views throughout the web app, I am wondering if I could possibly need to use an if statement to loop through each one of the elements in my project. I’ve read some posts about looping through the entire selection of data for example ??

Forms.py


class FormData(forms.ModelForm):
  

class Meta:
   model = assignments
     lastAssignmentSelected = table1.objects.all()
     print lastAssignmentSelected
  #assignments_id = forms.CharField(selection = lastAssignmentSelected)
  fields = "__all__" 

Views.py


class getlastAssignmentSelected(View):
    def data(self, request, *args, **kwargs):
        form = FormData(request.POST)
        if form.is_valid():
            options_value=request.POST['assignments']
  value=request.POST['value']
    form.save()
     print(table1,options_value)

return render(request, 'main/lastAssignmentSelected', context={"assignemnts":table1, "value":options_value})

As you can see, I’ve also tried incorporating the form class with form.ModelForm as well, but still haven’t been able to get it right.

I think at this point you need to break this down into its separate parts and look at this piece by piece. I’m getting the impression that you’re getting confused between what’s happening in the server in Django and what needs to happen in the browser in JavaScript.

So let’s start with the very beginning, and the JavaScript you need to call the view. Ignore everything else for now.

Do you have working code that lets you select an element on your page, create the correct url, and issue the request to the server?

If yes, we can proceed to the next step. (If not, lets get this working first.)

Hi. Thanks for your response. As far as I can make out the only working code related to selecting an element on the current web page is either:

selectAssignment = document.getElementById('assignments');

OR


document.getElementById("assignments").innerHTML = lastAssignmentSelected;

I am sure the following url could work if lastAssignmentSelected is the variable that determines the option value that is returned in the new table:


path('getfirstAssignemntSelected/<lastAssignmentSelected>', views.getfirstAssignmentSelected, name='lastAssignmentSelected')

But, as for issuing the request to the server - I am not sure whether that would look something like the following example from Django Responses and Objects:


if request.method == "GET":
    do_something()
elif request.method == "POST":
    do_something_else()

Let me know what you think ?
Otherwise, I would be so glad to start from the beginning and get this working.

As far as I understand, I only have Javascript that is meant to be a section of code that results in values being brought into a new table. I think when you say Javascript needed to call the view - I immediately think of the getfirstSelectedAssignment view that I’ve defined and expect to act as the view where the table reads lastAssignmentSelected.

I thought you were trying to trigger this request based upon selecting something from a drop-down?

I’m referring to this select list:

And this event listener:

This is the JavaScript code that is going to call the Django view by issuing the http request.

Is this working as desired?

Hi. I apologize. I do not know how to check whether this call has been made successfully. I do not know whether to check if -


lastAssignmentSelected = e.target.options[e.target.selectedIndex].text;

is working. OR
whether -


console.log("assignments:", lastAssignmentSelected)

is working.

Please guide me here.

You’re using that to create a url that the fetch call is going to use.

Are you generating the correct url?

You can either use console.log in your JavaScript to check that value, or look at the request being issued on the server to see the url being requested.

OK. YES. the code above allows me to select an element inside table1. On the Task Schedule web page

I think I have checked now and in my web browser’s javascript Console, no values can be seen. I am not 100% sure ?

Is the fetch issuing a request to the correct (desired) url?

According to me it is, because that is the same as the url path in the urls.py file ??

Not necessarily - The url you are submitting is supposed to have a parameter on it, lastAssignmentSelected.

If you make a selection from the select list, is the correct parameter being created as part of that url? Is the value you are sending what the view is going to expect?

Not at this point - if I make a selection in the table on the web page, basically nothing happens apart from that column switching to that selection. No parameter as part of the url. But yes I think the value that will be sent once the user has made the selection is expected as the view getfirstAssignmentSelected.

a screen grab of how it is setup

And it looks like you have the event handler connected to the Year element, correct?

So what happens if you change the Year? Does it trigger the event handler? Does the event handler cause the fetch to issue a request? And you’re saying that this request does not include the parameter?

yes. that would be the portion of code I initially sent. Below is the part with the actual field I’d like to trigger the event handler on…


<td class="Assignment"> {%csrf_token %}
<select onchange="onChange(e)" name="Assignments" id="assignments">
<option value="optionText1">screening_results_reports</option>
<option value="optionText2">ighid_12046</option>
<option value="optionText3">ighid_12022</option>
<option value="optiontext4">amc_099</option><option value="optionText5">sll_qHPV</option>
<option value="optionText6">colpo_LEEP</option>
<option value="optionText7">clinical_admin_stocktake</option>
<option value="optionText8"></option>
</select>

No. the event handler isn’t being triggered. I can’t see, but I don’t believe the event handler is causing the fetch to issue a request either.
There is no additional parameter linked to the request, it would be simply the names of these tasks directly as is I think.

Ok, first:

  • Remove the onchange attribute from the select element. (See HTML attribute reference - HTML: HyperText Markup Language | MDN for why I’m suggesting this.)

  • Keep these two lines, but move them to the bottom of that script. Also suggest you change the name of your event handler from onChange to something else to prevent confusion with any built-in API. (I’m suggesting selectChanged below):

  • Enclose that code within the DOMContentLoaded function to ensure the table is loaded before it’s activated.
document.addEventListener("DOMContentLoaded", (event) => {
   var selectAssignment = document.getElementById('assignments');
   selectAssignment.addEventListener('change', selectChanged);
});

This replaces the two lines above.

Finally, in your selectChanged method:
lastAssignmentSelected = e.target.value;

You want to avoid using arbitrary text in a URL because of the possibility of it containing characters not suitable for a URL. Use the value instead.

OK. This is great ! thank you so much for your direction. We are getting somewhere.
There was a response returned to the table now, however it is an error, a MultiValueDict, and I am reading up on it - so far I can make out that there is an issue with the form not having a field attributed to it. Not 100% sure here though and not sure if this is related to the [key]. I am sharing a screen shot as well as the traceback related to the forms.py file because I am accessing the table cell by using {{ form.data }} - simply by trial and error. I think the form FormData might need some work.

Screen grab:

Traceback error:

from schedule_app import views
File "/Users/andrewchibwesha/Visual Studio Projects/test_app/schedule_project/schedule_app/
views.py", line 7, in <module>
from schedule_app.forms import FormData File
"/Users/andrewchibwesha/Visual Studio Projects/test_app/schedule_project/schedule_app/
forms.py", line 86, in <module>
class FormData(forms.ModelForm):
File "/Users/andrewchibwesha/Visual Studio Projects/test_app/schedule_project/.venv/lib/python3.12/site packages/django/forms/models.py", line 299, in __new__
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: 
Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form FormData needs updating.

Looking forward to this last part.