Hey there everyone, I was wondering how to send both single and multiple values to a database using JavaScript and JSON endpoints with a Spring Web API

{
        "id": 178,
        "stockin_date": "2022-11-15T08:18:54.252+00:00",
        "effective_date": null,
        "expired_date": null,
        "create_date": null,
        "update_date": null,
        "createby_emId": null,
        "updateby_emId": null,
        "deleteby_name": null,
        "delete_date": null,
        "invoice": "P_008",
        "po": "YSYDV",
        "remark": "Buy from PIC",
        "supply_id": 2,
        "stockinDetail": [
            {
                "id": 272,
                "quantity": 10,
                "unit": "kg",
                "unit_price": 9,
                "stockin_id": 178,
                "pro_id": 74
            },
            {
                "id": 273,
                "quantity": 14,
                "unit": "kg",
                "unit_price": 2,
                "stockin_id": 178,
                "pro_id": 75
            }
        ]
    }

How Can I Develop a JavaScript function to send this data to an API endpoint like Postman?

Hello everyone, does anyone know how to use JavaScript to submit both single and multiple values to a database using JSON?

Answer №1

If you want to make a POST request using fetch in JavaScript, you can follow this example with different data and a different url.

To customize the code for your specific needs:

  • Update
    const data = { "name": "test", ... };
    to
    const data = { "id": 178, ... };
  • Modify
    const url = 'https://dummy.restapiexample.com/api/v1/create';
    to
    const url = 'http://localhost:8082/stockin/add';

const data = {
  "name": "test",
  "salary": "123",
  "age": "23"
};
const url = 'https://dummy.restapiexample.com/api/v1/create';

//send the POST request and handle the response
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

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

Access JSON data from PHP server and display it in a listview on an Android platform

I have successfully developed a web service and now I am looking to retrieve the JSON object in order to populate data into an Android list view. Below is my PHP code snippet: $sql_query="SELECT * FROM testtable"; $query=mysqli_query($con,$sql_query); $ro ...

Leverage JavaScript to add the rel=0 attribute to a specific URL

Currently, I am integrating videos into my WordPress website using a plugin and I'm looking for a way to ensure that all the YouTube URLs contain rel=0 to eliminate related videos at the end. Can anyone suggest the best approach to achieve this? Any ...

Create messages similar to StackOverflow's "toast" notifications

When developing my web application, one aspect that constantly occupies my thoughts is the presentation of messages to the end-users. I've experimented with message boxes similar to those found in windows applications, but they tend to look unpleasin ...

What is the best method for removing node and then reinstalling it using nvm?

In my Mac, I have successfully installed Nodejs, but it was done using the usual method. However, in my new role, I've been asked to utilize NVM for Node installation. Can you guide me on the best approach to uninstall Node and then reinstall it with ...

Using Django to showcase model data using primary key

I have a project where I need to display multiple images in separate Owl carousels when clicked. The setup is correct, but for some reason the images are not loading into the carousel. Any help would be greatly appreciated. Here is my models.py: from djan ...

JavaScript facing issue with $.get command executing in incorrect order

I have encountered an issue with my JavaScript code where it is not running in sequence. The script includes an unload function that uses the $.get jQuery command to fetch a file, which is then supposed to be printed to an external device. To debug this ...

The list countdown for loop only appears in the initial iteration

Hey there, I'm currently facing an issue with duplicating my JavaScript countdowns and displaying images of cards on each loop iteration. Strangely, the countdown only appears in the first instance even though it's within the loop. I'm seeki ...

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

What causes my useEffect hook to trigger twice in React?

I'm currently utilizing @preact/signals-react in my react project for integration purposes. Encountered a challenge that requires resolution. Interestingly, I discovered that by removing import { signal } from '@preact/signals-react', the ...

Error encountered when attempting to perform a Fetch POST request with same-origin credentials (Express & React)

I'm currently testing a login process in React that reaches an Express API route; the HTTP request is a POST made using fetch as shown below: const response = await fetch(`http://localhost:3001/login`, { method: "POST", mode: "same- ...

Utilizing an Office App Ajax that includes an authentication header, the application connects to a secure Web API 2 backend with CORS

I am currently in the process of developing a content panel application for Office. As part of this project, I need to authenticate an account against a server. To accomplish this, I have implemented my own AuthorizationFilterAttribute on my web api 2 con ...

extracting data from JSON string using PHP

$example = '{"data":[{"BP":"94"},{"BP":"99"},{"BP":"85"},{"BP":"84"},{"BP":"95"}]}'; I need help decoding this JSON object using PHP. $decoded_array = array(); $decoded_array = json_decode($example, true); var_dump($decoded_array); Currently, ...

Is there a way to minimize the use of .value in Vue 3?

After recently diving into Vue 3, I find myself struggling to grasp some key concepts of the composition API. My current challenge involves converting a library from Vue 2 to Vue 3, where a reactive property named layout is being passed down to child compo ...

The object you are attempting to use does not have the capability to support the property or method called 'after'

When attempting to add a div tag dynamically using javaScript, I encountered an issue with the .after function not working in IE9+. The error message "SCRIPT438:Object doesn't support property or method 'after'" appeared in the console. If a ...

The Step function within AWS Lambda returns the error code "Runtime.HandlerNotFound"

Issue: Encountering a Runtime.HandlerNotFound error message when attempting to execute a Step Function with Lambda functions: Runtime.HandlerNotFound in step: SolarEdgeOvervie Possible Cause: { "errorType": "Runtime.HandlerNotFound", ...

Challenges faced when parsing JSON in Lua

I've encountered an issue with the code below: PerformHttpRequest('http://ossie.dk/API/verify.json',function(err, text, headers) local r=json.decode(text) for s,t in pairs(r.servers)do print(t) end end,"GET","",{}) The ...

Increasing the Efficiency of Styled Components

It appears to me that there is room for improvement when it comes to checking for props in Styled Components. Consider the following code: ${props => props.white && `color: ${colors.white}`} ${props => props.light && `color: ${c ...

Transforming a JSON data string into a DataTable using Newtonsoft.Json in VB

Here is the string I am working with: [{'Column1': 'c1r1', 'Column2': 'c2r1'},{'Column1': 'c1r2', 'Column2': 'c2r2'}] In Visual Basic, I am trying to convert this string into ...

Creating a new object through manipulation of existing objects

In my attempt to transform an existing object into a new object structure, I am facing some challenges. Here is the current data set: const jsonStructure = { "a11/a22/animations": "snimations", "a11/a22/colours": "sl/colours", "a11/a22/fonts" ...

The issue with executing event.keyCode == 13 in Firefox remains unresolved

I've implemented a function that sends comments only when the "enter" key is pressed, but not when it's combined with the "shift" key: $(msg).keypress(function (e) { if (event.keyCode == 13 && event.shiftKey) { event.stopProp ...