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

Determine the size of a BSON object before saving it to a MongoDB database using

I am currently in the process of determining the best way to calculate the size before storing certain data in MongoDB. After writing a script that parses and combines data into a single document, I have encountered an error when trying to use instance.sav ...

How to retrieve the image source from a block using jQuery

Currently, I am working on developing a slider for my webpage using jquery's "Cycle" plugin. However, I have encountered an issue with accessing the image sources used in the slider. To provide more context, here is a snippet of code from the 'he ...

Guide on transferring Javascript array to PHP script via AJAX?

I need to send a JavaScript array to a PHP file using an AJAX call. Here is the JavaScript array I am working with: var myArray = new Array("Saab","Volvo","BMW"); This JavaScript code will pass the array to the PHP file through an AJAX request and displ ...

What is the process for establishing the default type for an Activity Entity in Microsoft Dynamics?

Currently in the process of restructuring a portion of script code associated with the Fax Activity Entity within Microsoft Dynamics. Within the script code, the following can be found: document.getElementById("regardingobjectid").setAttribute("defaulttyp ...

Transform Vue military time to regular time format

I am retrieving the arrivalTime from todos.items. As I fetch the arrivalTime, it is sorted using the sortedArray function(), which converts the times to military time. Is there a way to change the sorted military time values to standard time format after s ...

How come my Ajax call is setting the 'Content-Type' to 'application/x-www-form-urlencoded' instead of 'JSON' as specified in the dataType parameter?

I have encountered an issue while responding to a button click using the code snippet below. The console.log() confirms that the function is being called, but the HTTP request it generates contains the header "Content-Type: application/x-www-form-urlencode ...

The Execution of a Function Fails When Passed to a Functional Component

My functional component accepts a function called addEvent, which expects an event parameter. The problem arises when I try to call this function from props within another functional component, as the function does not seem to execute: const onOk = () =&g ...

Is there a way to transition an element from a fixed layout position to an absolute layout position through animation?

I am looking to create a dynamic animation effect for a button within a form. The goal is for the button to move to the center of the form, while simultaneously undergoing a horizontal flip using a scale transform. During the midpoint of this animation, I ...

What is the best way to calculate the number of squares required to completely fill a browser window in real-time?

I am creating a unique design with colorful squares to cover the entire browser window (for example, 20px by 20px repeated both horizontally and vertically). Each square corresponds to one of 100 different colors, which links to a relevant blog post about ...

Leveraging Python for retrieving data with duplicate names from a JSON array

Apologies in advance if I am not using the correct terminology, as I am new to Python. I have a JSON array with 5 sets of data, each containing items with duplicate names. While I can extract these duplicates in Java, I am struggling to do so in Python. Th ...

The post request with Postman is functional, however the AJAX post request is not working. I have thoroughly reviewed the client-side JavaScript

I encountered a problem with an endpoint designed to create an item in my application. Sending a POST request through Postman works perfectly fine, as I am using Node.js and Express for the backend: router.post("/", jwtAuth, (req, res) => { console.lo ...

What is the best way to determine if a Google Apps user is not an administrator?

We have developed an app for Google Apps and incorporated the "Integrate with Google" button [https://developers.google.com/apps-marketplace/button]. One issue we're facing is that when a user clicks on this button, they must be an administrator. Howe ...

Dynamically add Select2 with a specific class name: tips and tricks

I need help adding a new row with a select2 instance using a class name. The new row is created with the select dropdown, but I am unable to click on it for some reason. var maxGroup = 10; //add more fields group $(".addMor ...

What could be causing NgModel to fail with mat-checkbox and radio buttons in Angular?

I am working with an array of booleans representing week days to determine which day is selected: selectedWeekDays: boolean[] = [true,true,true,true,true,true]; In my HTML file: <section> <h4>Choose your days:</h4> <mat-che ...

What could be causing the stack overflow in this (partial) MergeSort Implementation?

As I'm working on my own version of MergeSort, which implements recursion with a base case, the only issue I have yet to address is how arrays are imperfectly halved when their length % 2 != 0. For now, I require arrays of a length that is a power of ...

Using JavaScript and Codigniter to populate a drop down box with an array

One of the key elements in my Codeigniter project is the $location variable, which is set using sessions and can represent cities like 'Austin', 'Houston', and so on. Each location has its own unique tours to offer. Instead of manually ...

The menu item fails to respond to clicks when hovering over the header background image

I'm having an issue with the Menu Link not working. I can click on the menu item when it's placed inside the body, but when I try to place it over the background header image, it stops working. Any help would be greatly appreciated. <div clas ...

What is the best way to retrieve the current quality label from JWPlayer using JavaScript?

My goal is to retrieve the Current Quality Label from JWPlayer 7 using JS, but instead of getting the defined labels like 360p, 480p, 720p, I'm only receiving numbers such as 1, 2, 3... This is what I've tried: playerInstance.getCurrentQuality( ...

What is the best way to retrieve the value of a property within a JavaScript object?

I am facing an issue with retrieving the value of the status property from an object in my code. Below is a snippet of what I have tried: console.log("Resource.query()"); console.log(Resource.query()); console.log("Resource.query().status"); console.log(R ...

Recreating dropdown menus using jQuery Clone

Hey there, I'm facing a situation with a dropdown list. When I choose "cat1" option, it should display sub cat 1 options. However, if I add another category, it should only show cat1 options without the sub cat options. The issue is that both cat 1 a ...