Reload the page when submitting in a form that consumes an API

0

I have a form in a modal window, which makes a POST to an API on the server, and then the server saves the information in the DB. The server is made with Node Js and express. The problem is that when doing the submit, the IP address of the API is opened, and what I need is that the main page of my application is reloaded. Also, how do I capture the response from the server if the operation was successful or there was an error ... here the frontend code:

<form action = {apiUrl} method = "POST">
    <div className = "booking-checkOut">
      <label >Check Out: </label>
      <input type = "date" min = {minDate} name = "checkOut" required />
    </div>
    <div className = "booking-pasajero">
      <input name = "idPasajero" placeholder = "Nro identificacion" />
      <input name = "pasajero" placeholder = "pasajero" required/>
      <input type="email" placeholder ="email" />
      <input name = "nacionalidad" placeholder = "nacionalidad" />
    </div>
    <div className = "booking-booking">
      <p>Datos de la Reserva</p>
      <input type = "number" name = "cantPas" placeholder = "Cantidad de Pasajeros" min = "1" required/>
      <input type = "number" name = "tarifa" placeholder = "tarifa" step = "0.01" min = "10" required/>
      <textarea name = "observ" placeholder = "Observaciones"></textarea>
    </div>
    <input type = "hidden" name = "room" value = {props.data.roomNumb} />
    <input type = "hidden" name = "checkIn" value = {props.data.checkIn} />
    <input type = "hidden" name = "habitacionId" value = {props.data.roomID} />
    <button type = "submit" className = "modal-btn primary">Confirmar</button>
  </form>
  <button
   className = "Modal-close"
   onClick={props.clickCerrar}
   ></button>

and on the server I have this route:

app.post('${API_BASE}/new-booking', (req, res) => {
  data(req.body)
      .then (pgdata => {
        res.send("ok")
      })
      .catch(err => console.log(err))
}

that receives the data of the form and with the data function saves it in the database.

Greetings

    
asked by amblador 04.12.2018 в 02:31
source

2 answers

1

What is happening is that you are making the request directly from the form, this can be done as long as the server makes a re-address. In this case it is most convenient to make the request with JS, adding the following code to your page.

JS

async function submitHandler() {
  try {
    // Obtener los valores del formulario
    const checkOutEl = document.getElementsByName('checkOut')[0];
    const checkOut = checkOutEl.value;

    const idPasajeroEl = document.getElementsByName('idPasajero')[0];
    const idPasajero = idPasajeroEl.value;

    const pasajeroEl = document.getElementsByName('pasajero')[0];
    const pasajero = pasajeroEl.value;

    const emailEl = document.getElementsByName('email')[0];
    const email = emailEl.value;

    const nacionalidadEl = document.getElementsByName('nacionalidad')[0];
    const nacionalidad = nacionalidadEl.value;

    const cantPasEl = document.getElementsByName('cantPas')[0];
    const cantPas = cantPasEl.value;

    const tarifaEl = document.getElementsByName('tarifa')[0];
    const tarifa = tarifaEl.value;

    const observEl = document.getElementsByName('observ')[0];
    const observ = observEl.value;

    const roomEl = document.getElementsByName('room')[0];
    const room = roomEl.value;

    const checkInEl = document.getElementsByName('checkIn')[0];
    const checkIn = checkInEl.value;

    const habitacionIdEl = document.getElementsByName('habitacionId')[0];
    const habitacionId = habitacionIdEl.value;


    const formData = { checkOut, idPasajero, pasajero, email, nacionalidad, cantPas, tarifa, observ, room, checkIn, habitacionId };

    if (checkOut && idPasajero && pasajero && email && nacionalidad && cantPas && tarifa && observ && room && checkIn && habitacionId) {

      const url = '/api/post';

      const method = 'POST';

      const config = {
        method,
        headers: {
          'content-type': 'application/json',
        },
        body: JSON.stringify(formData),
      };
      // petición
      const response = await fetch(url, config);
      if (response) {
        // respuesta del servidor
        if (response.ok) {
          // obtener los datos de la respuesta
          const data = await response.json(); // puede ser .text(), .blob(), .arrayBuffer() o formData().
          // hacer algo con los datos ...

          // recargar página
          window.location.reload();

          // reiniciar valores del formulario, descomentar si no desea regarcar la página
          // checkOutEl.value = null;
          // idPasajeroEl.value = null;
          // pasajeroEl.value = null;
          // emailEl.value = null;
          // nacionalidadEl.value = null;
          // cantPasEl.value = null;
          // tarifaEl.value = null;
          // observEl.value = null;
          // roomEl.value = null;
          // checkInEl.value = null;
          // habitacionIdEl.value = null;
        }
      }
    } else {
      console.log('parametros no validos');
    }
  } catch (error) {
    console.error('submitHandler', error);
  }
}

HTML

<form onsubmit="event.preventDefault(); submitHandler()">
    <div className="booking-checkOut">
      <label>Check Out: </label>
      <input name="checkOut" type="date" required />
    </div>
    <div className="booking-pasajero">
      <input name="idPasajero" placeholder="Nro identificacion" />
      <input name="pasajero" placeholder="pasajero" required />
      <input name="email" type="email" placeholder="email" />
      <input name="nacionalidad" placeholder="nacionalidad" />
    </div>
    <div className="booking-booking">
      <p>Datos de la Reserva</p>
      <input type="number" name="cantPas" placeholder="Cantidad de Pasajeros" min="1" required />
      <input type="number" name="tarifa" placeholder="tarifa" step="0.01" min="10" required />
      <textarea name="observ" placeholder="Observaciones"></textarea>
    </div>
    <input type="hidden" name="room" value={props.data.roomNumb} />
    <input type="hidden" name="checkIn" value={props.data.checkIn} />
    <input type="hidden" name="habitacionId" value={props.data.roomID} />
    <button type="submit" className="modal-btn primary">Confirmar</button>
  </form>
  <button className="Modal-close" onClick={props.clickCerrar}></button>
    
answered by 06.12.2018 / 15:42
source
0

to the button you may need to add e.preventDefault (); or maybe with the response from the server you need to validate the client so that if it gives you the answer that you hope you can reload the page

    
answered by 04.12.2018 в 03:01