Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
SPA forms handling with Dataform Javascript - Not leaving form info in URL

I am working with express, mongoose and JavaScript to create a single page application. The code works , except I dont want to keep form info in the URL with post request. I tried redirect but it kind ended in loop - I think.

I am not using form method="post" because it will redirect the page and this is a SPA. I would like not to show this or redirect from the URL to the same page without the query info.

http://localhost:2000/?firstName=John&lastName=James&age=40

This is the form (index.html) --

<form id="formId">
      <input type="text" name="firstName">
      <input type="text" name="lastName">
      <input type="text" name="age">
      <button type="submit" onclick="processForm(event)">Save</button>
</form>

Here is the JS for the form handling :

function processForm(event){
  var formData = new FormData(document.forms[0])
  const queryString = Object.fromEntries(
    Array.from(formData.keys()).map(key => [
    key, formData.getAll(key).length > 1 ?
    formData.getAll(key) : formData.get(key)]));
  postData(queryString);   
}

async function postData(data) {
  fetch('/people', {
    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);
  });
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since this is an SPA application and you want to handle the form via AJAX, you should stop the default form handler for the page (which is a redirection).

You can do that using event.preventDefault()

So your code should look like this:

function processForm(event){
  event.preventDefault();
  ...rest of the form handling logic
}

Additionally you probably want to use the form.onsubmit event rather then button.onclick event to send the data.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda