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

363
Visualizações
Select code in EJS based on form value without refreshing the page in Expressjs

I have this drop-down in ejs where I need to show a default image, and a custom image when something is submitted in the form. But I want to do this without refreshing the page.

Important: The submit button is not necessary for me, so change of image by just clicking in drop-down will also be a solution for me.

index2.ejs


    <form action="/users/details" method="POST">
      <fieldset>
      <select class="selectpicker" data-style="btn-info" name="selectpicker">
        <optgroup label="Select Starting Station">
            <option value="" selected disabled hidden style="text-align:center">From</option>
            <option name="table1" value="1">1</option>
            <option name="table2" value="2">2</option>
        </optgroup>
        </select>
        
      <input type="submit" id="submit-form" />
      </fieldset>
  </form>

  <% if(imgsrc == 0) { %>
    <img src = "/images/default.png" />
  <% } else if(imgsrc == 1) { %>
    <img src = "/images/1.png" />
  <% } else if(imgsrc == 2) { %>
    <img src = "/images/2.png" />
  <% } %>

and users.js

var variabled = 0;

router.get("/index2", function(req, res, next) {
  console.log(variabled);
  res.render("index2", {title: 'some data', imgsrc : variabled});
  variabled = 0;
});

router.post("/details", function(req, res, next) {
  variabled = req.body.selectpicker;
  console.log(variabled);

  res.redirect("/users/index2");
})

This code works fine, but the page is refreshed everytime I click on submit. I want the image to change without refreshing the page.

I have guesses about ajax and event.preventDefault() but I don't know how to implement them.

Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can creat seprate route for posting data to the server.

app.post('/test', (req, res) =>{
const testObject = {
    name:'John Doe',
    email:'john@email.com'
};
res.json(testObject);
});

At client side you can use [fetch API][1] make a post request.

fetch('http://example.com/test', {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
},
headers: {
    'Content-Type': 'application/json'
    // 'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: JSON.stringify(data) // body data type must match "Content-Type" header
)
.then(res => res.json())
.then(data => { return console.log(data)})
.catch(err => { return console.log(err)} )

You can also use XMLHttpRequest in browser.

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