Having trouble displaying JSON response in Firefox console with Django

Code Snippet:

from .views import get_data

app_name = 'javascript'
urlpatterns = [
    path('', views.index, name='index'),
    path('api/data', get_data, name='api-data'),

]

Views.py:

from django.http import JsonResponse

def get_data(request):                
    dictionary = {'Name':'John'}
    return JsonResponse(dictionary)

def index(request):
    return render(request, 'javascript/index.html')

Index.html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
    method: "GET",
    url: "/api/data/",
    success: function(dictionary){
        console.log(dictionary)
    },
    error: function(error_data){
        console.log("errorrr")
        console.log(error_data)
    }
})
</script>

When trying to load the index.html file, I am using AJAX to print the contents of a dictionary. However, the Ajax call seems to be failing as indicated by the console log output:

errorrr
127.0.0.1:8000:30:3
Object { readyState: 4, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), catch: catch(), … }

I suspect there might be an issue with how my jQuery code is written. Can anyone spot a mistake in its implementation?

Answer №1

Revise the urls.py file as follows:

from .views import fetch_data

app_name = 'webdev'
urlpatterns = [
    path('', views.home, name='home'),
    path('api/data[/]?$', fetch_data, name='fetch-data'),

]

The AJAX call is made to 'api/data/', but this does not align with the defined path

path('api/data', fetch_data, name='fetch-data')
. By changing it to 'api/data[/]?$', the URL will now match whether or not it includes a trailing slash.

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

Listening for events on an array of elements using jQuery

My task involves populating an array with elements using the .each() method and the $(this) selector. (function($){ var elements = new Array(); var index = 0; $("img").each(function() { if($(this).attr("attribute")){ $(thi ...

Drag a spinning cube using CSS and Jquery when the mouse is pressed

I'm attempting to develop a dynamic rotating cube that users can manipulate to their desired side by clicking and dragging on the cube. Currently, I have functionality where the cube moves as the mouse cursor moves across the screen, but this results ...

Retrieving JSON data from PHP using jQuery

I've been struggling with this issue for two whole days now, and I feel like I've hit a dead end in trying to solve it on my own. Here's the situation: I have two pages - one that contains a form with an address field that gets auto-filled ...

Validation of JSON Failed

Encountered a 400 Bad Request error while attempting to POST an answer using Postman, it appears to be a validator issue. Despite multiple attempts, I have yet to resolve this issue. Below are details of the JSON data being sent in the POST request along w ...

Creating a customized JSON object with Laravel framework

Hey Team, I'm facing an issue with structuring my JSON output correctly. What I have in mind is the desired output below: { comments: { data: { created_at: "date", other: "etc", from: { username: ...

Altering the color of numerous labels using ajax jQuery and .NET Core MVC

I have developed a feature that allows users to choose answers using radio buttons. Once the user has selected all answers and clicked Submit, the answer labels will be displayed in the following three scenarios: If the user selects the correct answer lab ...

Sending data via POST when clicking on a jQuery UI autocomplete result

I'm attempting to send the id value of the selected item to the search.php file using POST. While it functions properly with GET, it does not work when using POST. Below is the code snippet I currently have: $( function() { $( ".search" ).autoco ...

Python script for extracting content from iframes without specified sources

Currently, I am attempting to extract the content within an iFrame with the ID "topic" from the following HTML file: https://i.stack.imgur.com/FustQ.png Even after trying methods like Selenium and Beautiful Soup, I am still unable to access the elements i ...

Using timedelta to filter data when a field may be missing

I'm attempting to develop a function within the PlayerAt table to retrieve records from a PlayerOc table based on a filter that utilizes the timedelta feature. Below is an abbreviated version of the class: class PlayerAt(Base): id_ = sa.Column(sa ...

Form using Ajax technology, including two drop-down menus sourced externally

Is there a way to automatically populate a second drop-down list with all models once a selection is made in the first drop-down on a form? Below is the code snippet: <form> <div class="landing_quote_left"> ...

What is the process for sending a JSON request?

Review the structure provided { "layer_id":"1Wn", "name":"Example Place", "latitude":"45.5037078163837", "longitude":"-122.622699737549", "span_longitude":"0.62", "extra":{ "description":"Portland", "url":"http://en.wikipedia.o ...

Utilizing Multiprocessing in Python for Grid Search and Parameter Optimization

I'm currently working on optimizing the efficiency of a grid search for a Python function that requires two input values (a lower threshold and an upper threshold) by leveraging multiprocessing. After referencing resources like , I attempted the follo ...

A Comparison of Python MVC Framework, .NET, and Rails in Terms of Middleware

Exploring a fresh project and in search of the ideal technology for maintaining a Middleware Layer. This layer is aimed to provide REST and SOAP Webservices for multiple devices (mobile and web). The two main requirements are speed and ease of setup with ...

Exploring the contrast in Python Requests package's treatment of data and json parameters

What distinguishes the data from the json parameters in Python's Requests library? The documentation available at this link does not provide a clear answer. Consider this code snippet: import requests import json d = {'a': 1} response = re ...

Execute a series of Promises (or Deferreds) consecutively and have the flexibility to pause or stop at any point

Having an issue here. Need to make numerous consecutive http calls and the ability to stop the process at any point in time. The current solution I have involves jQuery and Deferreds, but it lacks proper interruption handling (still haven't transition ...

SQLite in Python: TypeError in Update Statement - Function requires 2 arguments but only 1 given

There seems to be an issue that keeps popping up findSenGroup = cur.executemany("UPDATE SEN_Table SET SenNumber = " + senNumStr + " WHERE FormName='" + nameGroup + "'") TypeError: function takes exactly 2 arguments (1 given) error when using t ...

Retrieve token and ETH value for an ERC20 transaction using the Etherscan API

I am embarking on my journey with the etherscan API for the first time. My objective is to efficiently extract data from a wallet, specifically focusing on "Token Transfer ERC20", and then be able to calculate the ROI of the wallet. To achieve this, I wil ...

Issue with passing arguments for entry_points in Setuptools

I have developed a Python script and I am using setuptools Once the installation is complete, I run: $ megazord -i input -d database -v xx-xx -w yy-yy Just like how I would run it as ./like_this However, I encounter the following error: Traceback (mos ...

When trying to append in jQuery, the error "JQuery V[g].exec is not a

Attempting to create a script that adds a table to a div within the website using the following function: function generateTable(container, data) { var table = $("<table/>"); $.each(data, function (rowIndex, r) { var row = $("<tr/>"); ...

What is the best way to effectively test jQuery's .ajax() promises using Jasmine and/or Sinon?

There is a simple function that returns a jQuery .ajax() promise: CLAW.controls.validateLocation = function(val, $inputEl) { return $.ajax({ url: locationServiceUrl + 'ValidateLocation/', data: { 'locationNam ...