A step-by-step guide for invoking a JSON-based API

I'm currently facing an issue with calling a JSON-based authentication API. The API requires two parameters, username and password, to be passed in JSON format.

What could be the mistake in my approach? Below is the snippet of my current test code:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>API Testing Page</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>API Testing Page</h1>
        <button id="btn">test</button>
    </header>
    <p id="result"></p>
    <script>
        const xhr = new XMLHttpRequest();

        xhr.onload = function () {
            const serverResponse = document.getElementById("result");
            serverResponse.innerHTML = this.responseText;
        }

        xhr.open("POST", "url");
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.send("username=test&password=test");
    </script>

</body>
</html>

Answer №1

Give this a shot.

Try using the following code to make a POST request with JSON data:
xhr.open("POST", "url");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({ username: "test", password: "test" }));

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

creating a distinctive JSON data structure in Node.js

I have a JSON dataset that looks like this, var data = [ { _id: 5abb46b060808f3a2096f91d, patient_name: 'krishnaaaannnn', gender: 'male', charge_id: 5ab243ac73959deb3ad79fec, description: 'suffering from pain' ...

Change the class of the div when the first div is selected

My goal is to switch the class of the #klapp element (from .klapp to .klappe) whenever a click event happens inside the #label-it container, including when the #klapp element itself is clicked. The challenge is that I am not able to use unique IDs for each ...

How should .has(), .get() and .set() be properly implemented for a JavaScript Map() within an ExpressJS server?

Feeling thrown off by javascript Map()? My query revolves around javascript Map() - the set, get, and has() functions. Despite thinking I was an expert, it seems I still have things to learn... Situation: I'm dealing with a 'global' map sto ...

Is there a method to determine if localForage/indexedDb is currently handling data operations?

Currently, I am working on a webapp that utilizes async localForage (specifically angular localForage). My goal is to alert users if they attempt to close the browser window while there are ongoing localForage operations. I have observed that some browser ...

PHP jQuery buttons for popovers

With a simple click of a button, I can generate 8 presentations and then edit each one individually by clicking on its respective name. Within this editing process, there is another form where I would like to include additional buttons that allow me to cus ...

Different method for interpreting json using Newtonsoft.json and mapped to C#.net models

My thread title may not be the best, so if you have a better one in mind, please let me know. I am currently working on existing code that utilizes Newtonsoft.JSON to read JSON from a .JSON file provided by a third-party source. The JSON is mapped to an ex ...

Locate all elements in an array that contain a particular value for a specific key using Javascript

In my JavaScript data, I have two arrays: ARRAY ONE: [ TextRow { v_id: 3000 }, TextRow { v_id: 3001 }, TextRow { v_id: 3002 } ] ARRAY TWO: [ TextRow { s_id: 'S001', v_id: 3000, type: 'control' }, TextRow { ...

Elements that are added dynamically will not inherit the correct CSS styles, requiring JavaScript to style them properly

My <ul> element dynamically adds <li> elements, and I am attempting to make the first <li> wider at 63% while the others are at 60%. However, the first one is only getting a width of 60%. Any thoughts on why this might be happening? I ne ...

Having Trouble with My Loot Table in Fabric 1.15.2

Hi there, I'm new to minecraft Modding and I prefer using fabric because it's more user-friendly. I'm having trouble with the loot table for my block, can anyone help me out? This is the code I have: { "type": "m ...

What is the best way to pause before executing the next npm command until the current command finishes running?

At first glance, creating an 'init' command seems like a straightforward task. However, as I dive deeper into the process, challenges start to surface. The goal is to develop an 'init' command that assists in preparing a cloned repo fo ...

Problematic redirect following jQuery AJAX request

I am facing an issue with my code where the page is redirected to the index page of my website after the AJAX method completes, but the redirected page appears empty with just a background. function login(){ var uname = document.getElementById("UserNa ...

Updating a property in an object within an Angular service and accessing it in a different controller

I am currently utilizing a service to transfer variables between two controllers. However, I am encountering difficulties in modifying the value of an object property. My goal is to update this value in the first controller and then access the new value in ...

Customizing File Size and Dimensions in Form Submission with Dropzone.js in JavaScript

I am currently experimenting with some sample code for Dropzone.js and am interested in finding a way to include the file size as a form field when submitting: var KTFormsDropzoneJSDemos = { init: function(e) { new Dropzone("#kt_dropzonejs_exam ...

What is the best way to utilize $.ajax with text, images, and checkboxes in web development

One challenge I'm facing is posting a form using AJAX, which can contain text, messages, and checkbox values. All this data needs to be sent to a PHP controller. I've always used $.post for simple text chats, never $.ajax. Below is an example of ...

Typescript: defining an interface that inherits properties from a JSON type

When working with TypeScript, I've utilized a generic JSON type as suggested in this source: type JSONValue = | string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue} My goal is to cast interface types matching JSON to and ...

How come the date displays as 21/1/2015 instead of 21/1/2015 in Android after parsing the JSON data?

Currently, I am utilizing the DatePicker functionality in my code and transmitting the value via JSON. The desired format for the value is 21/1/2015 without the extra backslashes. How can I resolve this issue? DatePickerDialog.OnDateSetListener date = n ...

Differences between using a getter in Vue.js/Vuex compared to directly accessing state values on the create lifecycle hook

As I utilize the created lifecycle hook within vue.js to fetch data from my store and pass it to a vue component's data, an interesting observation arises. When I employ this.selectedType = store.state.selectedType, the data is successfully retrieved ...

initiate scanning for HTTP GET calls

My current project involves using electron to create an application that serves multiple image files through a webserver using express. Another app built for Android is responsible for retrieving and posting files to this server. While I have successfully ...

Struggling to properly implement the prepend logger feature in the code

A function I have created is capable of adding a specified string to the start of each line, whether using streams or a console.log()-like method. Below is the code for this function: // This function prepends a string to each line in a stream exports.lp ...

Creating synchronization mechanisms for events in JavaScript/TypeScript through the use of async/await and Promises

I have a complex, lengthy asynchronous process written in TypeScript/JavaScript that spans multiple libraries and functions. Once the data processing is complete, it triggers a function processComplete() to indicate its finish: processComplete(); // Signa ...