Having trouble fetching data values from an Ajax GET request in a Django view

Is there a way to query the employee list based on parameters sent through an ajax call within the data property? I want to use a GET request only, but it is returning an error.

AJAX Function in JavaScript

  $(document).ready(function () {
    $(".call_ajax").click(function () {
      $.ajax({
        url: "/employee_list",
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        data: {
          designation: "soft eng",
        },
        headers: {
          "X-CSRFToken": csrftoken,
          Authorization: my_token,
        },
        success: function (data) {
          console.log(data);
        },
        error: function (xhr) {
          //Do Something to handle error
          console.log(xhr.error);
        },
      });
    });

Backend View Code

@csrf_exempt
@api_view(['GET', 'POST', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
@authentication_classes([TokenAuthentication])
def employee_list(request):

    if request.method == 'GET':
        data_ = request.data['designation']
        print(data_)
        employees = Employee.objects.all()
        students = Student.objects.all()
        user = MyUser.objects.all()
        serializer = EmployeeSerializer(employees, many=True)
        serialized_sudents = StudentSerializer(students, many=True)
        multi = {
            'employees': serializer.data,
            'students': serialized_sudents.data
        }
        return JsonResponse(multi, safe=False)

Error Message in Browser

GET http://127.0.0.1:8000/employee_list/ 500 (Internal Server Error)

Django Log Showing Key Error

 File "C:\Users\atif\PycharmProjects\CodePlatform\syntax_fight\api_\views.py", line 42, in employee_list
    data_ = request.data['designation']
KeyError: 'designation'

Answer №1

When utilizing request.data, you are able to access the parsed content of the request body, much like with request.POST and request.FILES.

An alternative method involves using request.GET.get('designation').

@csrf_exempt
@api_view(['GET', 'POST', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
@authentication_classes([TokenAuthentication])
def employee_list(request):
    if request.method == 'GET':
        data_ = request.GET.get('designation') # Change made here
        print(data_)
        employees = Employee.objects.filter(designation=data_) # Connect parsed data with database field
        students = Student.objects.all()
        user = MyUser.objects.all()
        serializer = EmployeeSerializer(employees, many=True)
        serialized_students = StudentSerializer(students, many=True)
        multi = {
            'employees': serializer.data,
            'students': serialized_students.data
        }
        return JsonResponse(multi, safe=False)

Alternatively,

You can override the get_queryset method. Since request.data contains POST data, query string parameters can be accessed through request.query_params.

def get_queryset(self):
    data = self.request.query_params.get('designation')
    queryset = Model.objects.filter() # Implement desired filter criteria
    return queryset

For further details on request.data and request.query_params, refer to the following link: Request parsing link

Answer №2

Perhaps the issue arises because you are utilizing GET, while the data is located in the body of the request. Refer to this for more information. One potential solution is to switch your request method to POST:

      $.ajax({
        url: "/employee_list",
        type: "POST",
        ...

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

What is the best way to retrieve nested ng-include scope/fields within a form?

I've searched high and low but haven't found a solution to my unique issue. Just like many others, I'm facing the challenge of ng-include creating a new child scope that doesn't propagate to the parent. I have a versatile template tha ...

Using Typescript and webpack to detect variables that are defined in the browser but not in Node environment

My goal is to create a package that can be used on both servers and clients with minimal modifications required. Some libraries are available in Node but not in a browser, while others are accessible in a browser but not in Node. For instance, when utili ...

The functionality of ngSubmit and ngDisabled seems to be malfunctioning, although ngModel is successfully linked to the

Despite following the usual process of creating a form in AngularJS, the ngSubmit function is not working as expected and the ngDisabled feature is failing to disable the button when the fields are empty. I even tried isolating the section in a new project ...

What is the best way to incorporate dual login options using Django?

Is it possible to set up two types of logins using Django? For instance, 1. Employee login - Employee page 2. Supervisor login - Supervisor page. After several attempts, I finally managed to make it work with the following code: models.py from django.c ...

The toggle for hiding and showing, along with changing the button color, is not functioning properly due to

I'm encountering a puzzling issue with a toggle that hides and displays information and changes color on click. The functionality works flawlessly on the page where I initially wrote the code. For instance, the button's background shifts colors w ...

Why isn't the VueJS component loading state getting updated after Canceling an Axios network request?

Within my dashboard, there is a dropdown for filtering dates. Each time a user changes the dropdown value, multiple network requests are sent using Axios. To prevent additional API calls when the user rapidly changes the date filters, I utilize AbortContr ...

How can one gain access to a specifically generated element?

In my task of dynamically generating multiple elements, I am facing an issue related to accessing specific ones. To illustrate this problem as simply as possible, I have provided the following code: $(document).ready(function() { var num1 = 0; v ...

Error 404: MVC4 Ajax request not found

When I look at the browser console, it shows a 404 error for not being able to find the URL. The URL where it's making a POST request is http://localhost:54473/Date/GetArticleName. The method inside the DateController.cs public JsonResult GetArticle ...

Having difficulty transmitting a base64 video via Ajax Post to PHP

While attempting to upload a MP4 video with a size of 16.9 MB via ajax asynchronous post to a PHP file, an error is displayed in the console: POST net::ERR_EMPTY_RESPONSE It seems that the issue is related to the PHP memory_limit setting. When set to 200 ...

Counter is effective for the initial post, yet it does not function properly for the subsequent post

Can anyone help with an issue I'm having with my JavaScript counter? It works for the first comment, but not the second one. This problem persists whether I use PHP or JavaScript. Below is the JavaScript code for the counter: var count = (function() ...

Determine the presence of a JSON Value/Array in a web application using JavaScript and visualize the information in a dynamic

Utilizing the Ticketmaster API has provided me with a sample dataset from their platform, Data 1 - Including information on "presales." "sales": { "public": { "startDateTime": "2019-11 ...

NodeJS reference copying problem

After encountering an issue where changes to the original object were being reflected in a copy due to JavaScript referencing, I followed recommendations and updated my code as follows: const originalData = {...docid[0][0].Record} // or const originalData ...

Transforming javascript's array.map into php's array_map function

The following code snippet is written in JavaScript and consists of a hashmap array with keys and values. I have created a function using map that returns the values of the entered keys. var rule = { "c": "d", "a": "o", "t": "g", "h": "a", "e": "n", "n": ...

Upon installation, the extension that replaces the new tab fails to detect the index.html file

edit: Check out the Chrome Extension here Edit 2: It seems that the recent update containing the index.html file was not published due to Google putting it under revision. Apologies for forgetting to include the index.html file in the upload zip, as I ...

AJAX and Java combination causing issues with logging out in the system

I am working with AJAX using jQuery to trigger a function when clicking a link with the ID logOut. Here is the AJAX code: $("#logOut").click(function(){ $.ajax({ url: "Logout" }); }); This AJAX function calls my Java Servlet shown below: /** ...

Refresh WebPage automatically after a Servlet successfully uploads and processes an image

I have a webpage that includes an image and a button. When the button is clicked, it uploads the image by submitting a form to a file upload servlet. However, after successfully uploading the image, the servlet does not display it in the img tag. Here is ...

The MuiThemeProvider.render() function requires a valid React element to be returned, or null if necessary

I am working on creating a dropdown using Material UI and React. It renders perfectly when the dropdown component is in my src/app.js, but I encounter errors when I move it to a separate file named fruits.js: MuiThemeProvider.render(): A valid React el ...

Storing a Promise in a Variable in React

As a newcomer to JavaScript/React, I am finding it challenging to grasp the concept of using Promise and async. To illustrate, consider the API call getSimById in a JS file that returns a Promise: export function getSimById(simId) { return fetch(simsUrl ...

When retrieving data using $.ajax in WordPress, the response will be an object containing the fetched information

I'm struggling to figure out a coding issue as a non-programmer, even after searching online extensively. Within WordPress, I have inserted a JS script that allows me to input a domain and receive specific data in return. This script makes a call to ...

chosen option in dropdown remains when returning to this page after using AJAX in PHP

When an error occurs or for any other reason that redirects to the test.php page, the selected items in both dropdowns should be displayed. However, upon returning to this page, the province dropdown is selected while the district dropdown is not. How can ...