0

I have an express app with an index.js that has the following:

<form method="post" action="searchAll">
    <input type="text" name="keyword"/>
    <button type="submit">Submit</button>
</form>

This functions well as a form that takes a keyword and searches my database and then follows up with a POST of the results.

But can I have a button like this:

<button id="refreshDB">REFRESH DATABASE</button></br>

which doesn't send any data to the server other than calling a server side function? The function (located in app.js or db.js on the server) takes no parameters and doesn't follow up with a post request. I'm thinking something like the following:

<button id="refreshDB">REFRESH DATABASE</button>
<script>
    var button = document.getElementById('refreshDB');
    button.addEventListener('click', function() {

    // SOMEHOW TELL SERVER TO RUN FUNCTION
    // similar to the html <form method="post" action="refreshDB">?

    });
</script>

I know I'm missing something really basic. I have a basic understanding of routing, but have no idea how to use one for a simple one-way function call. All of the help I find usually uses a form to submit data. The ExpressJS documentation is helpful, but I can only find server side code when it comes to routes like this.

This popular question is asking something similar, but the answer uses a form.

Can help identify what basic 'thing' I am missing? Thank you!

Community
  • 1
  • 1
Richard
  • 336
  • 4
  • 12

1 Answers1

1

You need to do an AJAX call to your server (an API route) and then deal with the result.

An 'AJAX call' is an asynchronous HTTP request, that means that you won't have to reload your page to get the response of your request (unlike the form tag).

Make an AJAX call

Javascript (pure / Vanilla) [ON THE CLIENT SIDE]

function myAjaxCall(url, data, callback) {
  var req = new XMLHttpRequest();
  req.open("POST", url, true);
  req.send(data);
  req.onload = function(e) {
    if (this.status == 200) { // if the HTTP response code is 200 (OK)
      callback(e.responseText); // passing the result of the request to the callback function 
    }
  };
}

JQuery [ON THE CLIENT SIDE]

$.ajax({
  method: "POST",
  url: "http://your.server/route/url",
  data: "The data you want to send to your server"
}).done(function(res) {
  console.log(res); // the value returned by the server (deal with it)
});

EDIT : Making it work with the button [ON THE CLIENT SIDE]

var yourData = "The data you want to send to your server";
var url = "http://your.server/route/url";

var button = document.getElementById('refreshDB');
button.onclick = function(e) { // (almost the) same as addEventListener
  myAjaxCall(url, yourData, function uselessName(result) {
    console.log(result);
  });
}

Creating an API route with Express and Nodejs [ON THE SERVER SIDE]

I assume that you already have an Express server, so you have the app object.
Let's say that your server address is 'http://your.server'. The simpliest way to create a POST route (not the better if you're building a big app) is the following :

app.post('/route/url', function(req, res) {
  console.log(req.body); // this will output "The data you want to send to your server"
  var data = yourFunction();
  res.status(200).send(data); // the status 200 is the default one, but this is how you can simply change it
})

EDIT - here's what actually happen :

  • You click on the button, it enters into the event handler (the function after the onclick keyword)
  • It uses the function myAjaxCall
  • This function makes the request (Ajax call)
  • req.onload is called (because it recieve the response of the request, that mean the data coming from the server)
  • we use the function that is passed in parameter as 3rd argument of the myAjaxCall function and pass the result of the request as a parameter
  • this function (named uselessName because in reality it doesn't need a name) will just log the result.

Hope it helps,

Best regards

boehm_s
  • 5,254
  • 4
  • 30
  • 44
  • Hi! Thanks for the reply! I'm still working on it. So far I do have this working with a button, by putting the `req.send()` in the button function. But it looks like it only works once. All I have it do is a console.log. When I press the button a second time it give me this: `Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.` Any ideas? I'm new to AJAX so your detailed answer is very, very helpful. Thank you! – Richard Apr 24 '17 at 23:42
  • I've edited my post so it's easier to understand. 'AJAX call' and 'request' are synonymes. – boehm_s Apr 25 '17 at 00:16
  • Thank you boehm_s!!! You've helped me with a problem I've been dealing with for days. I now have a much better understanding of how to make things work between the client and the server. I hope this can help other beginners too. Thanks again. – Richard Apr 25 '17 at 18:00