Submitting data using JavaScript's POST method

I am facing a challenge with posting Array data to an HTTP connector. My data is structured as follows:

var data = [{ 
    key:'myKey',
    keyName:'myKeyName',
    value:'value',
    valueName:'valueName' 
}, { 
    key:'mySecondKey', 
    keyName:'mySecondKeyName',
    value:'secondValue',
    valueName:'secondValueName'
}, ...and so on ];

When attempting to post it via Ajax like this:

$.ajax({
    type:   "POST",
    url:    url,
    data:   data,
    error:  function(){
        alert("Error");
    },
    success: function(){
        alert("OK");
    }
});

The request returns fine, but the posted data appears as

undefined=value&undefined=secondValue

I need all this information for configurations. How can I resolve this issue? Simple posts with keys and values work perfectly fine.

Answer №1

Assuming you are sending a POST request with a JSON payload, it is important to ensure that your payload is properly formatted as JSON. You can check the formatting using this tool:

Next, when sending the payload, utilize JSON.stringify and set the contentType:

data: JSON.stringify(data), contentType: "application/json; charset=utf-8"

If you execute this code and inspect the network tab in Chrome's Dev Tools, you will see any potential errors, but also view the formatted payload being sent to the server: http://prntscr.com/f8hf6s

var data = [{
    "key": "myKey",
    "keyName": "myKeyName",
    "value": "value",
    "valueName": "valueName"
  },
  {
    "key": "mySecondKey",
    "keyName": "mySecondKeyName",
    "value": "secondValue",
    "valueName": "secondValueName"
  }
];

var url = "http://swapi.co/api/";

$.ajax({
  type: "POST",
  url: url,
  data: JSON.stringify(data),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  error: function() {
    alert("Error");
  },
  success: function() {
    alert("OK");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

The text color remains the same even after the method has returned a value

I have a vuex query that returns a list of books. I want to display each book with a specific color based on its status. I tried using a method to determine the color name for each book and bind it to the v-icon, but it's not working as expected - no ...

Trouble Displaying DHtmlX Scheduler Events on Safari and Internet Explorer

I have recently embarked on the journey of building a nodejs application and decided to incorporate DHtmlX Scheduler as my calendar. To my dismay, I encountered an issue where the events are not displaying on Safari or IE, despite working perfectly fine on ...

Guide on displaying a specific element from a JSON file following an Ajax request

Here is a snippet of JSON data I am working with: [{ "id": "1", "name": "Alice", "last_name": "Johnson", "SSN": "AJ123456789", "age": "35", "gender": "Female", },{ "id": "2", "name": "Bob", "last_name": "Smith", "SS ...

When you input text into a contenteditable div, it automatically gets placed inside a span element instead of being placed

I'm having an issue with my contenteditable div. Whenever I click the button, a span is inserted into the div. However, when I start typing, the text goes inside the span instead of outside it: jQuery(document).ready(function($) { let input = $(" ...

Issue - Following error occurred in the file connection.js located in node_modules/mysql2 library: Module not found: Unable to locate 'tls' module

I've encountered an error in our Next JS applications where tls is not found. I have tried several troubleshooting steps including: 1. Updating Node modules 2. Using both mysql and mysql2 3. Running npm cache clean --force 4. Removing node_modules di ...

Finding a specific object within an array of objects by searching through a key value pair

In my collection, I have an array of objects structured as follows: [{ "businessunit": [{ "Area": [{ "Asset": [{ "Wells": { "Well": "Well 11" }, "name": "Field ...

Issue with smart table sorting functionality

I've been working on a table with just one column that is populated from a string array. However, I'm struggling to get the sorting functionality to work properly. Can anyone pinpoint what mistake I might be making here? Steps taken so far: 1) ...

What is the best way to retrieve and save the titles of checked boxes in the Autocomplete using state with hooks?

I've implemented the React Material-UI Autocomplete feature with checkboxes in my project. Here is what I have so far in my code (check out demo.js for details): https://codesandbox.io/s/material-demo-rxbhz?fontsize=14&hidenavigation=1&theme=d ...

Is it possible for my code in ReactJS to utilize refs due to the presence of backing instances?

When working with ReactJS components, I often piece together JSX elements to create my code. For example, take a look at the snippet below. I recently came across this page https://facebook.github.io/react/docs/more-about-refs.html which mentions that "Re ...

Can you explain the variance between using querySelector() and getElementById/getElementsByClassName/getElementsByTagName()?

I'm confused about the distinction between using querySelector() and getElementById(). From what I understand, querySelector is able to retrieve an element using any selector, giving it more flexibility. Are there additional contrasts between the two ...

Advancement in the processing time of a HTTP response that is significantly prolonged

I am seeking a way to return an array of JSON objects (requested by an AJAX call in an AngularJS web application) that represent specific files on the server implemented with node.js. Typically, the result is quickly accessed from a database. However, if ...

What seems to be the issue with this particular jQuery collection?

Perhaps something quite simple but I am having trouble figuring it out. Below is the command that returns a json array. var zz = fm.request({ data : {cmd : 'url', target : hash}, preventFail : true, op ...

How can I show the total sum of input values in a React.js input box?

Is there a way to dynamically display the sum of values entered in front of my label that updates automatically? For example, you can refer to the image linked below for the desired output Output Image I have initialized the state but I'm struggling ...

Node.js process.exec() function allows you to asynchronously spawn a subprocess

After writing the code, I ran it and found that the terminal was unresponsive with no output, causing the program to be stuck. var util=require('util') var exec=require('child_process').exec; exec('iostat 5',function(err,stdo ...

Every time I switch tabs in Material UI, React rebuilds my component

I integrated a Material UI Tabs component into my application, following a similar approach to the one showcased in their Simple Tabs demo. However, I have noticed that the components within each tab — specifically those defined in the render method ...

Guide on creating rsa key pair on the client side with angular2

Is there a way to generate an 'rsa' key-pair on the client-side using angular2? I am looking to create a private/public key pair and store the private key in a database while using the public key on the client side. How can this be achieved? I c ...

Challenges with JavaScript objects while using d3.js

I have been working on rendering a map using d3 within an HTML page that is running on a django web framework. One of the examples I came across from d3's sample archives can be found at this link: http://bl.ocks.org/NPashaP/a74faf20b492ad377312 Upon ...

What could be the reason for the lack of read or write functionality in $cookies for angular version 1.6.6?

I am relatively new to working with Angular. I have started a test project and my goal is to store user authentication in cookies. Despite my best efforts, I keep encountering an undefined error when attempting to retrieve the stored value. I am not sure w ...

Despite being installed, the message 'concurrently: command not found' pops up

I'm attempting to run two scripts simultaneously, and I came across the concurrently package that is supposed to assist with this. After executing npm install concurrently --save and verifying it in my package.json, I faced an issue when trying to run ...

Sanitize input data prior to using express-validator in a Node.js application

In my Node.js project, I am utilizing the V4 syntax of express-validator as recommended: const { check, validationResult } = require('express-validator/check'); const { matchedData } = require('express-validator/filter'); Additionally ...