Reputation: 77
Just learning nodejs. I want to change content inside my html without completely rendering in the page when I post.
Here is my current code.
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs')
var arr = [];
app.get('/', function (req, res) {
res.render('index', {messages: null, error: null});
})
app.post('/user', function (req, res) {
var input = req.body.userInput;
var output = "";
arr.push(input);
for(var i = 0; i < arr.length;i++){
(function(){
console.log(arr[i]);
output +=arr[i] + "</br>";
})(i);
}
res.render('index', {messages: output, error: null});
})
app.listen(port, function () {
console.log('Example app listening on port 3000!')
})
Thanks. Any advice is really appreciated.
Upvotes: 0
Views: 5571
Reputation: 655
Send just the data:
app.post('/user', function (req, res) {
var input = req.body.userInput;
var output = "";
arr.push(input);
for(var i = 0; i < arr.length;i++){
(function(){
console.log(arr[i]);
output +=arr[i] + "</br>";
})(i);
}
res.status(200).json({messages: output, error: null});//Not rendering new page, just sending data
})
In the front-end, handle as follows if you're using plain JS:
function handlePostUser() { // Invoke this on form-submit or wherever applicable
var xhr = new XMLHttpRequest();
xhr.open("POST", 'your link/user', true);
xhr.setRequestHeader("Content-Type", "application/json");
var payload = { data to post };
xhr.send(payload);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && !xhr.status) {
// Handle error
console.log("FAILED");
} else if (xhr.readyState === 4 && xhr.status === 200) {
console.log("SUCCESS");
//your logic to update the page. No reloading will happen
}
}
}
Upvotes: 2
Reputation: 943510
You can't do that with server-side code.
You could have to write client-side JavaScript to manipulate the DOM of the existing page.
That JS could use Ajax to get fresh data from the server. You could either write client-side code to extract the portion you care about, or create a different server-side endpoint that only returns the bit of data you want.
Upvotes: 2