What could be causing the Error 400 message to appear when trying to upload a JSON file via an HTTP request?

This Code Snippet is Essential

function makeRequest() {
    var dataToSend = {
        "username": "234zu",
        "subject": "qwertz",
        "content": "qw",
        "created_at": "2018-12-15 22:18:54",
        "updated_at": "2018-12-15 22:18:54"

    }
    var jsonData = JSON.stringify(dataToSend)

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("response").innerHTML = this.responseText;
        }
    };
   
    xhr.open("POST", "url", true);
    xhr.send("jsonData")
}
Now, after sending the post request, I encounter a bad REQUEST error. However, when I make a POST using Postman, it goes through successfully. Here's how the successful response looks like: { "id": 844, "username": "234zu", "subject": "qwertz", "content": "qw", "created_at": "2018-12-15 22:18:54", "updated_at": "2018-12-15 22:18:54" }

Answer №1

Make sure you are sending the actual variable finish and not just the string literal "finish". To do this, stringify the request body using var finish = JSON.stringify(obj) before calling xhttp.send(finish).

Don't forget to set the content type with

xhttp.setRequestHeader('Content-type', 'application/json')
before making the send call.

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

Converting a jQuery DOM element into a string representation

Currently, I am working with a textarea that contains the contents of an HTML file. This textarea includes all elements of my HTML page such as doctype, head, html, etc. My goal is to save the content of the textarea into a DOM variable using $.parseHTML: ...

the slider HTML control is missing a value

Exploring the Range Input Type in HTML When adjusting the value on a slider (Range input type), that value is displayed in a textbox. However, making the same adjustment in the textbox does not update the slider's value. Below is the code snippet: & ...

What is the process for encrypting and decrypting image files over the internet?

I'm currently developing a web application that requires loading images into a canvas object, followed by extensive manipulation. My goal is to conceal the original source image file (a jpeg) in such a way that users on the client side cannot access i ...

Ways to extract a data point from the wunderground API in JSON format

I'm currently working with a JSON feed from wunderground.com. While I've been able to adjust and work with simpler formats based on the example code provided in the documentation, I've hit a roadblock with a specific issue. Despite my effort ...

Can the FB status update popup be displayed when clicked?

I've implemented a code on my website that allows users to update their Facebook status directly from the page: <head> <title>My Awesome Site</title> </head> <body> <div id="fb-root"></div> <script s ...

What is the best way to utilize URL parameters to dynamically update a component's state within a class component

I am currently working on a React component that is making calls to two different API URLs, and the fetch operations are functioning as expected. However, I would like to utilize the URL handle structure, which looks like localhost://site/coins/[handle], a ...

Unable to execute node in vscode terminal

Can anyone help me figure out why I'm unable to run Node in my vscode terminal? I'm a newbie and currently using POP OS 22.04. https://i.stack.imgur.com/WqHWM.pnghttps://i.stack.imgur.com/GEHeA.png Your assistance would be greatly appreciated. ...

The input field will be in a read-only state if it contains a value from the database. However, it will be editable if the value

Hello everyone, I am a newcomer to this community and would greatly appreciate your help. I am encountering an issue with the following lines of code: <input type="text" class="form-control" id="fines" name="fines&quo ...

How to fetch images from a database in CodeIgniter by utilizing JSON and AJAX functions?

Trying to retrieve an image using ajax/json format for the first time, all variables are displaying except the image. The name of the image is visible when inspecting the element in the browser and it is saving correctly into the image folder. I need help ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Setting up and using npm jshint with Grunt and Node.js

I have successfully installed node.js on Windows with the npm package. My project is located in the D drive at D:>projectD I am currently working on running jshint along with SASS, concat, etc. Everything seems to be working fine except for jshint ...

Discover the best way to integrate your checkbox with your Jquery capabilities!

I am having trouble getting my 3 checkboxes to interact with the JQuery button I created. The goal is for the user to be able to select an option, and when the button is clicked, the selected options should download as a CSV file from my feeds. Below is th ...

How can I use JavaScript to trigger a button click event inside an iframe element

Is there a way to retrieve the inner HTML contents of a clicked element in an iframe loaded content using JavaScript? This code uses jQuery: var elements = document.getElementsByTagName('iframe'); [].forEach.call(elements, function(elem ...

Session is required for req.flash() function in node.js to work properly

I recently started working with Node.js and I'm encountering an issue with sessions. I developed a simple application and tried to run it locally, but ran into some errors. Below are the details of my code along with the error messages: BAPS.js (app. ...

Eliminate any unnecessary tags located before the text

I am facing a challenge with the following code snippet. The Variable contains a string that includes HTML tags such as <img>, <a>, or <br>. My goal is to eliminate the <img> tag, <a> tag, or <br> tag if they appear befo ...

Is it possible for two Bootstrap icon class names to be used sequentially with one taking precedence over the other?

I am having an issue with toggling a class name in my code. I have a class named (bi bi-clipboard) and I want to change it to (bi-clipboard-check) when it is clicked. However, the problem is that the new class name gets added next to the existing one like ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...

Using nextJS to establish a context within a Server Component and incorporating a new library

I attempted to incorporate Framer Motion into my project, but when I added it, an error occurred. The error message displayed was: TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Fo ...

Process JSON data from an input using Javascript

I am encountering an obstacle at the final step of my data flow process. Currently, I am in the midst of developing an application that retrieves input from an HTML form field and utilizes Ajax to fetch data relevant to the user's input. Allow me to e ...

Using Angular's ng-switch directive within a select dropdown option

Can we implement the [Data Presentation Format] to be utilized in the [Dropdown Box]? Specifically, I would like the "parent" items to appear as is within the dropdown, while the "child" items should have a [tab] indentation to denote their relationship wi ...