Simple example of a button click with Ajax and Node.js?
I am new to Ajax and Node.js + Express. At this point I am trying to figure out how to communicate with the front and back using buttons.
I have a button on an HTML page that I would like to use to call a function from the backend and output text to the client.
Here's what I put together for what I need, but I'm looking for an example of how this can be done.
It all happens on / page
index.hjs file
<button class="btn btn-success" onclick="install()">Install</button>
// Client Side Ajax Script
<script>
$('button').click(function () {
$.post('/page', {data: 'blah'}, function (data) {
console.log(data);
});
}, 'json');
</script>
App.js file
app.post('/page', function (req, res, next) {
calling.aFunction();
res.write('A message!');
});
Are these all the parts I need and what do I need to edit for this functionality to work?
+3
source to share
1 answer
index.js
<button class="btn btn-success">Install</button>
// Client Side Ajax Script
<script>
$('button').click(function () {
$.post('/page', {data: 'blah'}, function (data) {
console.log(data);
});
}, 'json');
</script>
app.js
app.post('/page', function (req, res) {
calling.aFunction();
res.send('A message!');
});
You should see a "Message!" in the browser console.
+5
source to share