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
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.