What is the best way to incorporate JSON data within a "data:{}" object when making a POST fetch request?

Greetings to all the listeners, this is my first time reaching out for help.

I have put together a form and I am making a fetch request to my database system (Xano). Here is a snippet of how my JSON object looks:

{
  "job_type": "full-time",
  "job_title": "3D Art Director",
  "job_location": "remote",
  "job_level": "senior",
  "salary": "$600 day"
}

However, Xano requires the data to be nested one level deeper inside "data", otherwise I am unable to access it using dot notation...

{
  "data": {
    "job_type": "full-time",
    "job_title": "3D Art Director",
    "job_location": "remote",
    "job_level": "senior",
    "salary": "$600 day"
  }
}

Below is the JavaScript code I am using. Can anyone guide me on how and where to place the JSON response inside "data:"{} ? (I am new to JavaScript and my code is a mix of different sources as I am learning!)

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('jobForm').addEventListener('submit', handleForm);
  });

  function handleForm(ev) {
    ev.preventDefault(); 
    let jobForm = ev.target;
    let fd = new FormData(jobForm);

    //look at all the contents
    for (let key of fd.keys()) {
      console.log(key, fd.get(key));
    }
    let json = convertFD2JSON(fd);

    //send the request with the formdata
    let url = 'https://hookb.in/eKjeKejY6NhlaRPldLNP';
    let h = new Headers();
    h.append('Content-Type', 'application/json');

    let req = new Request(url, {
      mode: 'cors', // no-cors, *cors, same-origin
      headers: h,
      body: json,
      method: 'POST',
    });

    fetch(req)
      .then((res) => res.json())
      .then((data) => {
        console.log('Response from server');
        console.log(data);
      })
      .catch(console.warn);
  }

  function convertFD2JSON(formData) {
    let obj = {};
    for (let key of formData.keys()) {
      obj[key] = formData.get(key);
    }
    return JSON.stringify(obj);
  }

Answer №1

Here is an example of how you can convert FormData to JSON:

function transformFormDataToJSON(formData) {
  let json = {
    data: {}
  };
  for (let key of formData.keys()) {
    json.data[key] = formData.get(key);
  }
  return JSON.stringify(json);
}

Answer №2

To easily convert FormData to JSON, create the necessary object structure before serializing it:

function convertFD2JSON(formData) {
  const data = {};
  for (let key of formData.keys()) {
    data[key] = formData.get(key);
  }
  return JSON.stringify({ data }); // equivalent to { data: data }
}

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

Is it possible to utilize Flask in conjunction with jQuery's POST method?

I have just started learning Flask and before I move forward, I would like to know if it is possible to send a "post" request from jQuery to a Python function using Flask and JSON. I am not very familiar with JSON either, so all the code examples seem quit ...

In the present technological landscape, is it still considered beneficial to place Javascript at the bottom of web pages?

As a beginner in web programming, I've recently delved into Javascript. A hot debate caught my attention - where should javascript be placed, at the top or at the bottom of a webpage? Supporters of placing it at the top argue that a slow loading time ...

Error encountered: Unexpected character 'C' found at the beginning of the JSON data received during the Ajax callback

When checking the network debugger in the PHP file, it displays {message: "Success", data: {Name: "admin"}}. However, there seems to be an issue with the AJAX callback. Can someone help me troubleshoot this problem that has been bothering me for a while? T ...

Update the image on a webpage within a template using AJAX code

I manage a website that utilizes templates. Within the template, there is a main image that I need to replace on specific pages, not throughout the entire site. I am seeking a way to change this main image to a new one on select pages using Ajax. Upon re ...

Adding interactive elements within the <head> section of a Nuxt JS Application using information obtained from an API's response

In my current project with NUXT application, I am facing a challenge with adding dynamic content to the <head> section of specific pages. This content is generated from a one-time API response during the application initialization process (nuxtServer ...

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

Serializing intricate objects using JavaScript

I'm curious if there are any options outside of npm for serializing complex JavaScript objects into a string, including functions and regex. I've found a few libraries that can do this, but they all seem to depend on npm. Are there any good seri ...

Identify when an ajax request is completed in order to trigger a subsequent ajax request

Within my project, I am faced with a challenge involving select option groups that dynamically load ajax data based on previous selections. The issue arises when I attempt to replicate this functionality for another select option group. Here is the scenar ...

Scrolling will only function properly on this page if you refresh it

I have a setup where buttons on my first page lead to specific elements on the second page. To achieve this, I pass the element IDs in the URL like so: mysite.com/secondpage/:promo1(/2/3, depending on the button clicked.) Upon landing on the second page, ...

Recognizing the click event on the checkbox within a <TableRow/> in ReactJS with MaterialUI

Using ReactJS and MaterialUI's component for tables, I have successfully created a table with two rows, each containing a checkbox. Now, the challenge is to create a method that can recognize when a checkbox is clicked and provide information about th ...

I am looking to merge two tables in MySQL using a many-to-one relationship and retrieve a customized JSON output similar to the example provided below. How can this

How can I perform a MySQL join on two tables (many to one) and generate a specific JSON output as demonstrated below? Note: Please do not label this as a duplicate. Although there is a similar previous question posted, there are distinct differences that ...

Create a JSON object that organizes a collection with indexed items

Is there a library available that can generate a JSON object where a collection is represented as a set of numbered items? For example, when using the GSON library with a class like this: `class Bus { List<Passenger> passengers; ...

troubleshooting problems with feathers.JS using the npm start command

After developing two separate feathersJS applications, I encountered a situation where running npm start resulted in two unique types of errors for each app. How can I go about resolving this issue? View image here https://i.stack.imgur.com/RrsGW.pnghtt ...

Inquiring about the Model component within the MVC architecture in a web application created with NodeJs and integrated with

As a beginner in NodeJs, I am venturing into creating web applications using the express framework and MySQL. Understanding that in MVC architecture, views are represented by *.ejs files, controllers handle logic, and models interact with the database. Ho ...

Ways to modify client socket from JavaScript to PHP

Looking for a way to convert a client socket from JavaScript to PHP in order to receive data from the server socket? Check out the PHP socket Bloatless library here. This is an example of the Client Javascript code: <script> // connect to chat appl ...

Error: No schema found for the specified "User" model

Attempting to establish a connection with the MongoDB database using Mongoose and defining the model resulted in the following error message: MissingSchemaError: Schema hasn't been registered for model "User" Several approaches were taken to address ...

employing ajax for handling a form

Currently, I am facing an issue with updating a user's email on a page. The div refreshes upon submission as intended, but the database is not being updated, and I can't figure out why. My layout consists of a single page where clicking a menu l ...

Using the $http Angular service does not alter the passed array

Currently diving into Angular and facing a roadblock with the $http service and a JSON array. Within my code, there's an array labeled names. While I'm able to display its content within the function, an error pops up when trying to do so outside ...

Struggling to retrieve data from Firebase in React Native?

It's been a challenge for me as a newcomer to React Native trying to retrieve data from a Firebase database. This is the process flow of how my data is handled: 1. A user selects locations and trip details (name, startDate, endDate) --> stored in ...

A guide to pulling pictures from a database with the help of jquery and servlets

Currently, I am facing a challenge in retrieving images stored in my Oracle 11g R2 database. My approach involves using JQuery and servlet to fetch the images and displaying them within a CSS division. However, as I am unfamiliar with this process, I bel ...