Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

326
Visualizações
How to call server side function from html button (not in a form) using ExpressJS

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!

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda