Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple button click example with Ajax and Node.js?

I am new to both Ajax and Node.js + Express. At this point I am trying to figure out how to communicate with both the front and back end through buttons.

I have a button on an HTML page which I would like to use to call a function from the backend and output text to the client.

Here is what I've pieced together for what I need but I am looking for an example on how this could be done.

This is all happening 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 that I need and what needs to be edited to get this functionality to work?

like image 325
Web Hopeful Avatar asked Nov 26 '14 20:11

Web Hopeful


1 Answers

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.

like image 59
takinola Avatar answered Sep 19 '22 07:09

takinola