JavaScript 'Post' Request Triggered an Error

I've been encountering a "Bad Request" error while attempting to make a POST request. I would greatly appreciate it if someone could point out where I may have gone wrong.

function mkSentiTopics() {
    dta['n_clusters'] = 3;
    $.ajax({
        type: "POST",
        url: "http://saxonydemoubuntu.southcentralus.cloudapp.azure.com/sentitopic",
        data: JSON.stringify(dta),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(response) {
            alert("success");
        },
        beforeSend: function() {

        },
        error: function(xhr, stats) {
            alert("error");
        }
    });
}

The variable "dta" is in the form of a dictionary.

// dta["sentis"] consists of a list of numbers
// dta["texts"] consists of a list of strings
// dta["n_clusters"] is an integer value.

Answer №1

It seems that the error is caused by a mismatch between the structure of the data being sent to the server and what the server expects, resulting in rejection. Without knowing the specific API requirements, it's difficult to provide a precise solution.

Based on the information provided in your post, I will make an educated guess and offer the following suggestion:

// dta["sentis"] should contain numbers
// dta["texts"] should contain strings
// dta["n_clusters"] should be an integer.

When using JSON.stringify(dta), ensure that the output exactly aligns with what the API anticipates. Remember that JSON recognizes boolean, array, object, string, and number data types. It's important to note that true !== "true", 1 !== "1", and so forth.

For example:

let dta = {                 
  sentis: [1, 2, 3, 4],     
  texts: ["a", "b", "c"],   
  n_clusters: 5             
}

console.log(JSON.stringify(dta, 0, 1)); 

If the API mandates that the root key "dta" must be included, or if the structure needs adjustment, modify your dta object accordingly.

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

Accessing and fetching data from a PostgreSQL database using JavaScript through an API

I am currently working with an npm package called tcmb-doviz-kuru to fetch currency data from an API and then insert it into my database. However, I am facing an issue with mapping the data to properly insert the values. Below is my code snippet: var tcmbD ...

Inquiry regarding JSON data format

I am receiving the following response when I console.log(result): {"MSG":"WRONG","QUESTIONID":182.0} However, when I specifically target result.QUESTIONID and console.log it, I get: undefined Can anyone point out what mistake I am making? ...

Awaiting the completion of multiple asynchronous function executions

I am currently working on a promise function that executes an async function multiple times in a loop for different data. I would like to ensure that all async functions are completed before resolving the promise or calling a callback function within a non ...

Bypass the typical practice of choosing input with javascript

I have a form with a select input that has a dropdown list of options. The requirement is that when the select input is clicked, I need to validate the form. If the form is incomplete, I want to prevent the select input from showing the option list. Howeve ...

FoxyWeb Requests: Utilizing XMLHttpRequest in Firefox Extensions

While I've come across plenty of examples on how to create xhr requests from Firefox Add-ons, I'm currently exploring the new WebExtensions framework (where require and Components are undefined) and facing an issue with sending a simple XmlHttpRe ...

What is the reason for the jQuery plugin not being applied after replacing the page content with an Ajax response?

At the moment, I am utilizing jQuery ajax to dynamically add content to my website. Additionally, I have incorporated the jquery.selectbox-0.6.1.js plugin to enhance the style of select boxes on the page. The plugin successfully styles the select boxes up ...

What could be causing the discrepancy in the first and second socket request in my Node.js code?

Below is my echo server code snippet var net = require('net') var server = net.createServer(function(socket) { socket.write('Echo server\r\n'); socket.on(&ap ...

What is the best way to display an image/jpeg blob retrieved from an API call on screen using NextJS?

When using Next.js, I make an API call like this: const response = await fetch('/api/generateimageHG2'); This triggers the following function: import { HfInference } from "@huggingface/inference"; export default async function genera ...

Turn off logging functionality in a Node.JS environment

I am looking to turn off logging for specific environments in my Node.JS application using Express. Would the following method be considered the most optimal way to disable logging within Node.JS applications? if(process.env.NODE_ENV == "production") { ...

Is it possible to set up a universal type definition in TypeScript version 2 and above?

I have a collection of straightforward .ts files, not part of any projects but standalone .ts scripts. They implement certain node.js features. Both TypeScript and node type definitions are set up through the following commands: npm install -g typescript ...

The issue at hand is the lack of execution for the Mocha Chai `.end()`

I have encountered an issue while trying to write a Mocha chai test for a Nodejs API that was previously tested using Supertest. Strangely, the test always passes even when I intentionally specify wrong expected parameters. Below is the code snippet of th ...

the JavaScript anchor feature is malfunctioning

Steps to Play Back: To start, in the header section, select any of the links with anchors: ##bankaccount #pack #platform #acq ##scorecard ##intrade #form Next, scroll up to the top of the page Then, reload the page Actual Outcome: Upon reloading a page w ...

How can I update the state with the value of a grouped TextField in React?

Currently working on a website using React, I have created a component with grouped Textfields. However, I am facing difficulty in setting the value of these Textfields to the state object. The required format for the state should be: state:{products:[{},{ ...

What is the process for displaying a document file in an iframe that is returned from a link's action?

I have a main page called index.cshtml. This page displays a list of document files along with an iframe next to it. My goal is to load the selected document file into the iframe when I click on any item in the list. However, currently, when I click on a d ...

Avoid triggering a second event: click versus changing the URL hash

One of the pages on my website has tabs that load dynamic content: HTML <ul> <li><a href="#tab-1">TAB 1</li> <li><a href="#tab-2">TAB 2</li> <li><a href="#tab-3">TAB 3</li> </ul&g ...

Is there a way to download a file using an ajax request?

We are faced with a particular scenario in our application where: Client sends a request Server processes the request and generates a file Server sends the file back as a response Client's browser prompts a dialog for downloading the file Our appli ...

JavaScript visibility disappearing intermittently

I have created a custom image viewer box that overlays a thumbnail gallery page. The image viewer should appear when a user clicks on a thumbnail. However, currently, the viewer only pops up briefly and then disappears again. I am looking for a way to mak ...

Modify the code to interpret a new JSON structure

I have a piece of code that is designed to read JSON data: $.getJSON("data.json", function(data){ var output = ''; $.each(data, function(index, value){ output += '<li>' + value.title + '</li>'; } ...

Steer clear of directly accessing views in AngularJS using angular-ui-router

In my AngularJS App setup, I have the following configuration: angular .module('MyApp') .config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvi ...

Combining two sorted arrays in javascript while eliminating duplicate elements

Hello everyone! I am new to this and would really appreciate some assistance. I am struggling with merging two arrays and removing duplicates. I know I might be over-complicating things, but I just can't figure it out. // Merging two sorted arrays // ...