Django yielding a Null response following request.POST.get

As a newcomer to Django and AJAX, I am faced with the challenge of sending the ID of a dropdown list to a Django View using an ajax POST method. This ID is crucial for filtering a queryset and returning the corresponding row through AJAX. However, I have encountered a roadblock in applying the filter to the query set. It appears that the ID is being posted along with a variable containing 'None'. For example, when I print the variable sent in the POST request, it displays the ID followed by 'None', like this:

1748
None

This is a snippet of my HTML code:

<select id="drugSet">
{% for dose in dose_set %}
<option id="{{ dose.pubmed_id }}">{{ dose.drug_name }}</option>
{% endfor %}
</select>
<span id="drugName"></span>

Below is the relevant Javascript code:

function NeedDrugInformation() {
            var elementID = document.getElementById("drugSet");
            var strUser = elementID.options[elementID.selectedIndex].id;

            $.ajax({
                type: "POST",
                url: "drugsanddoses/",
                dataType: "text",
                async: true,
                data: { csrfmiddlewaretoken: '{{ csrf_token }}', drugID: strUser },
            });

            $.ajax({
                type: "GET",
                url: "drugsanddoses",
                dataType: "text",
                async: true,
                data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
                success: function (json) {
                    $('#drugName').html(json.drugInfo);
                    // $('.ajaxProgress').hide();
                }
            })
        }

In my views.py file, I handle the POST request as follows:

def drugsanddoses(request):

    drugIdentifier = request.POST.get('drugID')

    print(drugIdentifier)

    drugInfo = RiskCalculator.objects.values('drug_name', 'l_dose', 'h_dose', 'risk', 'pubmed_id', 'updated')

    response_data = {}

    try:
        response_data['drugInfo'] = str(drugInfo)
    except: 
        response_data['result'] = 'No details found'
        response_data['message'] = 'There is currently no information in the database for this drug.'

    return HttpResponse(json.dumps(response_data), content_type="application/json")

Answer №1

It appears that you have implemented a system that involves issuing two Ajax requests. One of the requests is a POST method and includes an ID, while the other request is a GET method without an ID, resulting in the response printing as "None". The rationale behind why two requests are being made is not entirely clear, but it seems to be the current setup.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop automatic image sliding by hovering in jQuery

How can I make the image slider pause on hover? Here is the code that I have been using: $(".col-md-8").hover(function() { clearTimeout(timer); }); It seems like this should work, but for some reason it's not. Can anyone ...

Utilizing a dynamic variable to define the URL in a getJSON request with jQuery

I'm currently working on a weather app using jQuery. One issue I've come across is with my getJSON function - I want to utilize a variable that I created with the current latitude and longitude coordinates. The openweathermap API key loads the JS ...

Encountering "net::ERR_EMPTY_RESPONSE" error when making a HTTP PUT request using the HUE API in JavaScript

GET requests are functioning properly. PUT requests made from the API Debug tool are also working correctly. However, both PUT and POST requests, regardless of the data or API URL used, are resulting in the following error: example: OPTIONS net::ERR_ ...

Issues with anchor tag click event in Firefox browser not functioning as expected

I have encountered an issue while trying to create an anchor tag in a TypeScript file. When clicking on this button, the anchor tag should be created. This functionality is working correctly in Chrome and IE, however, it seems to be not working in Firefo ...

Tips for assigning the result of a Fetch API call to a variable

Hello everyone! I'm currently working on a project that requires me to retrieve the latitude or longitude of a location using the Google Maps API. However, I am facing an issue with returning values using the Fetch API and its promises. I have succe ...

Nativescript encountered an issue while attempting to generate the application. The module failed to load: app/main.js

I'm currently experimenting with the sample-Groceries application, and after installing NativeScript and angular 2 on two different machines, I encountered the same error message when trying to execute: tns run android --emulator While IOS operations ...

Step-by-step guide on dynamically fetching additional images from a directory using php, jquery, and ajax

I have a scenario where I have multiple folders, each containing up to 20 images. On my HTML page, I want to display the first 5 images and provide a "click to view more" option to show the remaining 15 images when clicked. Currently, the issue I am facin ...

Including an identical field within the parameters of a MongoDB search query

In my mongodb collection testdata, there is a field named insertTime. Our goal is to remove data older than 60 days. Previously, to accomplish this, I would use the logic of finding the deletion date and then comparing it against the updateTime: var date = ...

Separate JavaScript/ASP statements using commas

I'm having trouble comma-delimiting this line in JavaScript, as I keep encountering errors: <a href="javascript:doSubmit(<%= pound & rs("AdvertiserID")%>, <%=rs("AdvertiserName")%>)"> It's Friday, what can I say... The &l ...

Redirect user if the parameter does not match the corresponding ID in the database using React Router V4

I need to handle the scenario where there is no matching lockId in my database by redirecting to the home route. I am retrieving locks from my Redux state. The following implementation achieves this: const lockId = this.props.match.params.lockId const lo ...

Validation of Arrays in Angular Schema Form

Trying to create an array of distinct values through Schema Form appears to be a challenging task. To simplify, let's examine this basic unique validator: $scope.validateUnique = function(value) { console.log('running validation'); ...

Determine whether the browser tab is currently active or if the user has switched to a different

Is there a way to detect when a user switches to another browser tab? This is what I currently have implemented: $(window).on("blur focus", function (e) { var prevType = $(this).data("prevType"); if (prevType != e.type) { // handle double fir ...

Upon encountering an expression, the code anticipated either an assignment or a function call, but instead found an expression, triggering the no

When using the forEach method within a function in JavaScript, I encountered a code compilation failure with the following error: Expected an assignment or function call and instead saw an expression no-unused-expressions. This error occurs for both ins ...

Converting Java date(milliseconds) to ExtJs Javascript Date

From the Java server side, I am receiving a date in milliseconds that I need to convert into a JavaScript Date object: long s = 1523357477; // At the Java end var v= new Date(1523357477); //At the Javascript ExtJS end However, the output is: Sun Jan 1 ...

List of random points generated using Three.js

Novice inquiry: I have generated some random points in JavaScript. How can I individually access each point later on? I remember something about an 'Object' that holds all the points, allowing me to manipulate their positions or selectively retri ...

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

Preserving the valuable AJAX response for future reference

My current task involves making AJAX requests within a JavaScript Interval function, specifically once every 10 seconds. The challenge I'm facing is figuring out how to store the response (text from the previous request) in a JavaScript variable. On ...

Are there any web servers specifically optimized for single page applications available?

When utilizing a single page application, the primary function of the webserver is to provide data upon client request (often in JSON format). Therefore, any server-side language (such as PHP or Ruby on Rails) or tool (like Apache or Nginx) can effectively ...

Understanding the Functioning of a Digital Analog Clock Using JavaScript

As a new learner, I found the operation of a Digital analog clock to be quite puzzling. I was presented with an image called clock.png, and I specifically struggled with how the hands of the clock function. Javascript - const deg = 6; // defining the valu ...

Issue with the status of a vue data object within a component

While working on updating my original Vue project, I encountered an error with the data object sports_feeds_boxscores_*. The website features three tabs that display scores for the major sports leagues. I am currently in the process of adding player stats ...