Send a POST request to the db.json file containing an object with various attributes

Here is the code snippet I am working with:

function createObject(){
  let object = {
    product1 : "Apple",
    product2 : "Banana",
    product3 : "Cucumber",
    product4 : "Duba",
    product5 : "Emil",
    product6 : "Fidschi",
  }

  return object
}

function commonAJAXPOSTCall(jsonstring){
  return $.ajax({
    type: 'POST',
    data: jsonstring,
    url: "http://localhost:3000/posts"
  }).then((response) => {
    return response
  })
}

export async function jsonDBSetter(){
    let object = createObject()
    //console.log(object)
    object = JSON.stringify(object)
    let resultCheck = await commonAJAXPOSTCall(object)
    console.log(resultCheck)

}

In my current setup, the data from the object is not being inserted into the "posts" table as desired. Instead of each property being stored in its own row with a "key => value" format, the JSON server combines all properties into one key and saves the entire JSON string under that single key.

As a newcomer to using json server, I have had difficulty finding resources that offer guidance specific to my needs...

UPDATE: I am seeking a solution that does not involve iterating through the object and making individual AJAX calls for each member of the JavaScript object.

Answer №1

Give this a shot :

return $.ajax({
    type: 'POST',
    data: jsonstring,
    contentType: "application/json",
    url: "http://localhost:3000/posts"
}).then((response) => {
    return response
})

If that doesn't work, you could attempt using FormData instead like so :

function createData(){
    let form_data = new FormData();

    form_data.append('product1', "Apple");
    form_data.append('product2', "Banana");
    form_data.append('product3', "Cucumber");
    form_data.append('product4', "Duba");
    form_data.append('product5', "Emil");
    form_data.append('product6', "Fidschi");

    return form_data;
}

function callingAJAX(formdata){
  return $.ajax({
    dataType: 'text',
    type: 'POST',
    contentType: false,
    processData: false,
    data: formdata,
    url: "http://localhost:3000/posts"
  }).then((response) => {
    return response
  })
}

export async function setDataInDB(){
    let formdata = createData()
    let result = await callingAJAX(formdata)
    console.log(result)

}

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

Mastering the art of utilizing defer/async attributes in script tags effectively

When I add the "defer" attribute to all external js files, Owl Carousel fails to load and shows an error that "$" is not defined. However, if I remove the defer attribute from the script tag, everything works fine without any errors. Unfortunately, I am un ...

Creating variables in styled-components allows you to easily reuse values throughout

Can a variable be defined inside a styled-components component? The code snippet below, although not functioning properly, demonstrates my intention: const Example = styled.div` ${const length = calc(vw - props.someValue)} width: ${length}; &. ...

The function `req.on('end', callback)` in Node.js is not functioning as expected

I am currently working on building a proxy using nodejs. The syntax I am using for sending and receiving https requests and responses works well, but in my project, I have noticed that the response is sometimes larger than expected. This results in req.on( ...

Exploring Node.js and Express routing: Strategies for managing client-side promises

I've been working on a routing issue with MongoDB where I'm having trouble retrieving data on the client side from the promise received via $resource. There's a button on the HTML page that triggers the following function on ng-click: $scop ...

Is it possible to precisely position multiple children in a relative manner?

I am currently developing a custom dropdown menu where I want the parent element to be relatively positioned within the page. The goal is for all the child elements of the dropdown menu (the list items) to appear as if they are part of a select element and ...

How to retrieve the value of a variable from one JavaScript function and pass it to another

As a JavaScript beginner, I am looking for help in retrieving values from one function to another. Specifically, I would like to access the values of dinoRight, dinoLeft, and others in the cactus1move function. const spawn = () => { const dinoRigh ...

What is the process for creating a dynamic URL, such as example.com/profile/CroatiaGM?

I am in the process of developing a user control panel, and I have encountered some difficulties with creating a dynamic profile link. For instance, how can I achieve something like example.com/profile/CroatiaGM? Given that my website is primarily coded ...

sending a pair of parameters from two dropdown menus to a controller method in Grails

I am currently working on a project where I have two dropdown lists - one depends on the other for its values. I also have a button where I need to pass the selected values from both dropdowns to a controller function for a query. Does anyone have any adv ...

Issues arising from URL encoded characters that fail to get rewritten

I have set up rules for dynamic redirects to point old URLs to new locations. However, I encountered an issue where the redirect failed when URL Encoded Characters were present in the URLs. Here is an example of such URLs: www.example.com/ebc-drama-yebet- ...

Is there a way to extract rows from a React MUI DataGrid that are identical to how they are displayed, including any filtering and sorting applied?

My goal is to make a selected row move up and down on arrow clicks, and in order to achieve this, I need to retrieve rows from the MUI DataGrid. I am using the useGridApiRef hook to do so, ensuring that the rows are filtered and sorted accordingly to match ...

Verify that a minimum of one checkbox has been ticked according to JavaScript guidelines, with appropriate notifications in case

Need help with displaying a message when no checkbox is checked. Currently implementing JavaScript rules and messages <form method="post" enctype="multipart/form-data name="english_registration_form" id="english_registration_form" > <div cl ...

The variable fails to receive the AJAX response

Trying to retrieve the content of data.dat, I have utilized the following code. Below are the relevant files: main.js function getData() { var result; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState ...

Database access limited to read-only for mysql operations

Currently, I am working on a small project where I have master-admin control over classic admin privileges. The database connection is established using a cookie named $key. If the cookie value is 'google', it accesses my master-admin database t ...

How can one elevate the properties of each item's sub-structure to the root level in an array containing object items?

I am working with an array containing objects, each with a specific structure... [{ user: { /* ... more (nested) user data ... */ }, vacation: { id: 'idValue', name: 'nameValue', startDate: 'dateValue', }, }, ...

sending numerous ajax requests and they all seem to be returning identical results

When firing multiple ajax requests using the setinterval() function, I noticed that both requests are bringing back the same information from another page. Here is the JavaScript code: function views() { setInterval(function(){var xmllhttp //alert ...

Where could I be missing the mark with AngularJS?

After following some tutorials, I managed to create my first test app. However, it doesn't seem to be working properly. The main objective of the app is to extract product information from a JSON file and display it using ng-repeat. Here are the rele ...

Creating point illustrations with Three.js

Looking to incorporate random points into a web project using Three.js. Here's the current code: <script type="module"> import * as THREE from 'https://threejs.org/build/three.module.js'; import { TrackballControls ...

A step-by-step guide on how to use ajax and node to save a file onto

Trying to save a file to the user's disk when they click on it using this ajax code: $('.cv_download').on('click',function(){ var fileName = $(this).text(); console.log(fileName) var temp = {"file" : fileN ...

An error pops up on the console every time I attempt to modify the quantity of items in the shopping

I'm having trouble with my shopping cart code in JavaScript. When I try to log the variables priceElement and quantityElement in the console, nothing shows up even though the tutorial says it should. Additionally, I'm getting an error message &ap ...

Determine whether a JavaScript string exclusively consists of punctuation marks

In an if statement, I want to verify whether the given string contains any punctuation. If it does contain punctuation marks, I intend to display a pop-up alert message. if((/*regex presumably*/.test(rspace))==true||(/*regex presumably*/.test(sspace))==tr ...