How to use the formData API to send a JSON Object that contains another Object?

I have created a HTML-form like this:

<form id="student__form">
    <div class="form__name-section">
        <div class="form__input-group">
            <label for="firstName">Firstname:</label>
            <input type="text" id="firstName" name="student['firstName']">
        </div>
        <div class="form__input-group">
            <label for="lastName">Lastname:</label>
            <input type="text" id="lastName" name="student['lastName']">
        </div>
    </div>
    <div class="form__info-section">
        <div class="form__info-section__left-column">
            <div class="form__input-group">
                <label for="address">Address:</label>
                <input type="text" id="address" name="address">
            </div>
        <div class="form__input-group">
            <label for="eMail">e-Mail:</label>
            <input type="text" id="eMail" name="email">
        </div>
    </div>
</form>

I am using the formData API in Javascript to parse the input-data into a JSON object. I read up on the formData API on this link.

Following the linked tutorial, I can easily obtain the form-input as a JSON:

{
  student['firstName']: 'Jennifer', 
  student['lastName']: 'Adams', 
  address: 'some address ', 
  email: 'jennifer.adams@gmail.com'
} 

It's almost what I want, but not exactly. I would like the student-information to be contained in an object itself:

{
  student: 
  {
    firstName: 'Jennifer', 
    lastName: 'Adams'
  } 
  address: 'some address ', 
  email: 'jennifer.adams@gmail.com'
} 

I'm not sure if this is possible though.

I would like this, because I am posting this JSON to my REST-endpoint, which currently throws an error - even though this error doesn't seem to be related to this issue, I still believe I need to fix my JSON. The error is a POST http://localhost:8080/employeeDetails 403. I am using Spring Security to Login to my App, so this 403 seems to be related to Spring Security, which I don't know how to fix either.

  function submitForm() {
    const form = document.querySelector("#student__form");

    form.addEventListener("submit",  e => {
      e.preventDefault();
      const data = new FormData(e.target);
      const formJSON = Object.fromEntries(data.entries());
      let responsePromise = fetch(
        "http://localhost:8080/studentInformation",
        { method: 'POST', body: JSON.stringify(formJSON) });
    })
  }


from Recent Questions - Stack Overflow https://ift.tt/3GXBKaw
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation