Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

369
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda