Guide on sending a JSON response from a POST request in JavaScript

After creating an API in Django that provides a JSON response based on a variable entered in the URL, I encountered a challenge with fetching and displaying this data using JavaScript.

For instance, consider this URL:

A sample of the JSON response looks like:

{"id": 1, "string": "iamnewtojavascript"}

Implementing a similar functionality in JavaScript has proven to be challenging for me despite searching extensively online for solutions.

In comparison, achieving this in Python is straightforward as shown below:

import requests
import json

url = "http://127.0.0.1:8000/api/string/IAMNEWTOJAVASCRIPT"

req = requests.post(url)
p = req.json()
data = json.dumps(p)
print(data)

Answer №1

To send a request in JavaScript, you can utilize the 'XMLHttpRequest' method. For more information, check out this resource.

Here's an example:

var dataToSend = {
    id: "1",
    string: "learningjavascript"
};

var httpRequest = new XMLHttpRequest();

// Callback function for readyState
httpRequest.onreadystatechange = function( ){
    if( this.readyState == 4 && this.status == 200 )    
        alert( this.responseText ) 
}

// Open connection to server
httpRequest.open("POST", /* URL GOES HERE */, true );
// Send the data
httpRequest.send( JSON.stringify( dataToSend ) );

This illustrates how to make a POST Request to the server. HTTP-Post-Requests are typically used for creating data on the server.

If you're looking to perform a HTTP-Get-Request instead, simply modify httpRequest.open("POST", ... ) to

httpRequest.open("GET", 'url', true );
and call httpRequest.send() without any parameter.

If you'd like further clarification on the distinctions between HTTP-Post-Requests and HTTP-Get-Requests, refer to this article.

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

Retrieving Image from Link for Django Web Application

My JSON file contains the following data: "Product_url": "https://www.amazon.in/Samsung-Galaxy-Storage-Additional-Exchange/dp/B07PQ7CRBH/ref=sr_1_11?keywords=phone&qid=1563166792&s=electronics&smid=A14CZOWI0VEHLG&sr=1-11&quo ...

When trying to access $model.show() in Vue.js, the returned model is showing as undefined

I'm running into a console error message every time I try to click the button for $model.show('demo-login'): TypeError: Cannot read property 'show' of undefined Error output when the button is clicked: TypeError: Cannot read prop ...

Steps for correctly invoking a function based on input value conditions

Lately, I've been developing a new website geared towards serving as a platform for various travel agencies to showcase their tour packages. The homepage features a functional filter section that enables users to search for offers based on different ...

Encountering a top-level-await issue while utilizing the NextJS API

Currently, I am in the process of creating an API using NextJS and MongoDB. To start off, I have set up some basic code at the beginning of the API file: const { db } = await connectToDatabase(); const scheduled = db.collection('scheduled'); Fol ...

Is it possible to utilize enums as keys in a Json structure?

I am currently utilizing TypeScript in conjunction with Node.js (MEAN stack). My aim is to incorporate an enum within the property/schema of a JSON object. An example of the enum would be: enum KeyEnums { A: "featureA", B: "featureB&qu ...

Steps for submitting a form once all inputs have been verified

$('#f_name, #l_name').change(function(){ if($(this).val().length < 2) { $(this).css('border', '1px solid red'); alert('names must be at least 2 symbols'); check ...

Error with Cross-Origin Resource Sharing (CORS) on my website

During the development of a website, I disabled web security in order to bypass CORS using the command chrome.exe --disable-web-security --user-data-dir=/path/to/foo However, after successfully completing the website and uploading it to my domain, I enco ...

How can I use jQuery to identify the numerical range within class/td/div elements and modify their CSS styles?

1# I need assistance in changing the CSS properties of a TD, Class, and div using a selector that specifies a specific number range. Specifically, I am looking to modify the css of torrent results with a seed count between 250-25000. Any torrents with a se ...

Exploring Material UI: Understanding the contrast in functionalities between incorporating the Icon component and the Material Icons node

I am looking to incorporate Material Icons into my application. I have come across two methods provided by Material UI for adding the same icon to my site: Using the <Icon /> component, which is part of the @material-ui/core package: <!-- Add t ...

Having Multiple Login Forms on a Single Page

I have encountered an issue with my login form code. It works perfectly as a single form, but I need to have 20 of these forms on one page. Despite my efforts to duplicate the code for each new form and adjusting the IDs, I am unable to make more than one ...

What is the best way to test a React component that includes a Router, Redux, and two Higher Order Components using Jest and Enzyme?

I'm currently facing a challenge with this issue. I have a React Component that is linked to React Router 4 and Redux store, and it's wrapped by two HOCs. It may sound complicated, but that's how it was implemented. Here's the export st ...

Is there a way to dynamically expand and collapse all table rows, with the latest row always remaining visible, using pure JavaScript?

I have a form input field where I enter data. The entered data is then displayed in a table as a new row, with the most recent entry at the top. What I want to achieve is to show only the newest row in the table and hide all other rows. When I hover over ...

Loop stops after completing one iteration

I am currently working on a program that automatically generates ASCII text based on input numbers. Essentially, when a number is provided as input to the function, it will be displayed as magnified ASCII text. For example, an input of 0123456789 would gen ...

Encountering Issues with Accessing Property

Upon trying to run my code, the console is displaying an error that I am unable to resolve. The error specifically states: "TypeError: Cannot read property 'author' of undefined." View the StackBlitz project here The error seems to be coming fr ...

What is the best way to extract the JSON data from a client-side GET request response?

Here is my request from the client side to the server in order to retrieve JSON data. fetch("/" + "?foo=bar", { method: "GET", }).then(response => { console.log(" ...

Alert: Zone.js has identified that the ZoneAwarePromise '(window|global).Promise' has been replaced with polyfills. Kindly address this issue

Recently, I updated my Angular application from version 8 to 9. After updating the packages and successfully compiling the application, I encountered an error message in the Chrome browser console: Error: Zone.js has detected that ZoneAwarePromise `(wind ...

The `user-select: none` property displays distinct behavior in Safari

My Goal I am in the process of creating an input-like content editable div. The idea is to click on tags outside the div and insert them inside the div while still being able to type around these tags. The Issue and Reproduction Steps To prevent tag but ...

CoffeeScript equivalent of when the document is loaded

Recently, I've been delving into Coffeescript for my web application, but I'm encountering a frustrating issue. The methods are not being called until I manually reload the page. I suspect that the missing piece may be the $(document).ready(func ...

Is it possible to implement drag and drop functionality for uploading .ply, .stl, and .obj files in an angular application?

One problem I'm facing is uploading 3D models in angular, specifically files with the extensions .ply, .stl, and .obj. The ng2-upload plugin I'm currently using for drag'n'drop doesn't support these file types. When I upload a file ...

The AJAX request is not triggered before the postback when using a LinkButton in ASP

I am facing an issue with running an insert statement using a button in my application. Although it is functional, I have noticed that whenever I click the button, the Page_Load function runs before the ajax statement executes. How can I ensure that the a ...