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

Discover the sequence that is the smallest in lexicographical order possible

Here is the question at hand Given a sequence of n integers arr, find the smallest possible lexicographic sequence that can be obtained after performing a maximum of k element swaps, where each swap involves two consecutive elements in the sequence. Note: ...

Retrieve the HTML data and save it as page.html, displayed in a VueJS preview

After developing an innovative VueJS-based application for managing front-end content, I am now eager to enhance it with a 'download' button feature. This new functionality will allow users to easily download the previewed and edited content in H ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

Upon redirection, my JavaScript codes cease to function properly and require a page refresh to resolve

Upon redirecting to another page with included JS codes, my main.html does not function properly until I refresh the page. What steps can be taken to resolve this issue? 0.html <body data-theme="b"> <div class="p2" data-role="page" id="p2"> ...

The next.js router will update the URL without actually navigating to a new page, meaning that it will still display the current page with the updated URL

My search results are displayed at the route /discovery, and I am working on syncing the search state with URL query parameters. For example, if a user searches for "chicken," the URL becomes /discovery?query=chicken&page=1. When a user clicks on a se ...

What is the best way to eliminate the space underneath a graph?

Despite trying multiple solutions, I'm still struggling to remove the excess blue space below the graph that appears when clicking the submit button. Any insights into what might be causing this issue? JSFIDDLE Below are the CSS styles related to t ...

Identify the currently active subitem within the item-active class in a PHP carousel slider

I am working on creating an image carousel slider with 4 items and 4 slides each. These images will act as radio buttons, and I want to highlight the slide corresponding to the selected radio button. So, when the carousel loads, the selected slide should b ...

What is the best way to simulate fetch in Redux Async Actions?

When writing tests in the Redux Writing Tests section, how does store.dispatch(actions.fetchTodos()) not trigger the fetch method when store.dispatch is directly calling actions.fetchTodos? The issue arises when trying to run similar code and encountering ...

The challenges of updating AngularJS partial templates and handling refresh in 2-way binding

I've encountered an issue with a partial template that's loaded outside of my ng-view, complete with its own controller. Here's a breakdown. Basic template layout <html ng-app="myApp"> ... <div ng-include src="'myPartia ...

The messaging feature is not functioning properly within the page tab

The iframe page tab is not compatible with the Send dialog. I followed the example on the 'Send Dialog' page https://developers.facebook.com/docs/reference/dialogs/send/ <html xmlns:fb="https://www.facebook.com/2008/fbml"> <body> ...

What significance do the variables c and d hold in the context of bubble sort implementation in the C programming language?

Regarding the ascending order bubble sort, the process involves checking if index i is greater than index "i + 1". If it is, then a swap occurs, and this continues until the loop reaches its end. The loop repeats until all indices are in order, resulting i ...

Having trouble with React testing-library: Why is the file upload empty when testing a PDF file?

While testing file upload with react-testing-library, I encountered an issue where the log indicated that the file was empty (even though it worked in the browser). After researching various docs and bugs, I discovered that since tests run on Node.js, the ...

Is there a way to simultaneously apply the :active pseudoclass to multiple elements?

<div id="a">A</div> <div id="b">B</div> <div id="c">C</div> <style> #a, #b, #c { height: 100px; width: 100px; background-color:red; font-size: 100px; margin-bottom: 20px; } ...

Solving templateUrl resolution of directives in Angular with RequireJS

Currently, I am using AngularJS and RequireJS in my single-page application (SPA). To organize imports efficiently, I rely on RequireJS. With RequireJS, I can utilize features like baseUrl to resolve import paths seamlessly. Now, I wish to apply the same r ...

Angular2: Filtering an array based on the presence of items in another array

Looking to selectively filter out entries from an object array based on certain id values within another array. I've experimented with different methods but haven't found a solution that works yet. List of id´s: list = [1,3] Array to be filte ...

Fetching data from MongoDB, loading over 3000 entries and implementing pagination

I'm facing a challenge where I need to display more than 3000 results in an HTML table by fetching MachineID, Username, and Data from my MongoDB. However, I am encountering difficulties when trying to render this data using datatables. The MachineID ...

Firestore - Using arrayUnion() to Add Arrays

Is there a way to correctly pass an array to the firebase firestore arrayUnion() function? I encountered an issue while attempting to pass an array and received the following error message: Error Error: 3 INVALID_ARGUMENT: Cannot convert an array value ...

Switching code from using .hover() to using .click() while still maintaining the functionality of both.orChanging code to switch

How can I change this script to trigger on click and also maintain the hover functionality: $x = jQuery.noConflict(); $x(document).ready(function () { $x(".swatch-anchor").on('click hover', function () { var newTitle = $x(this).attr( ...

Combining Django's CSRF token with AngularJS

I currently have Django running on an Apache server with mod_wsgi, and an AngularJS app being served directly by Apache rather than through Django. My goal is to make POST calls to the Django server that is utilizing rest_framework, but I am encountering d ...