Mojtaba
Mojtaba

Reputation: 743

Nodejs - How to send data from html to hapi

I'm trying to pass a value from my front end to my back end in Node.js as you may know there is not much documentation for Hapi in the net and most of the tutorials use angular.

I want to simply pass a variable from my front end (HTML) to back end in Hapi.

index.html

 <script>
      $('#messages').submit(function(){
        var word =  $('#m').val();
        //alert(word);
       $('#m').val('');
       return false;
      });

    </script>
  </body>

So what should I do here in order to pass the value? Thanks

P.S: I searched but couldn't find questions similar to mine.

Upvotes: 0

Views: 1569

Answers (1)

Alan Bogu
Alan Bogu

Reputation: 775

First of all, you do not need jquery to pass the value, the user could do it straight from html form like so:

<form id="messages" action="./your/path/" method="POST">

  Your variable:
  <br>
  <input type="text" name="your_variable" value="your_value">
  <br>

  <input type="submit" value="Submit">

</form>

If you have some reason for using a script use AJAX with $.POST inside the submit() callback:

$('#messages').submit(function() {

  $.post("./your/path/", {
      your_variable: "your_value"
    })
    .done(function(data) {
      alert("Data Loaded: " + data); // change for whatever callback you want
    });

  return false;
});

Check out jquery documentation to read up on $.post more.

And on the back end side, pick up your variable in the handler from request.payload:

server.route([{
  method: 'POST',
  path: '/your/path/',
  config: {
      payload: {
          output: 'data'
      }
  },
  handler: function (request, response){
    var your_variable = request.payload.your_variable
  }
}]);

Some useful hapi.js documentation links: request object, server route, route configuration, route handler.

Also, I'd recommend you to refresh your knowledge on HTTP protocol: wikipedia page on HTTP and a new MEAP book on HAPI.js that is avaiable on manning.org - I have learned hapi.js from it, absolutely brilliant: Hapi.js in Action

Upvotes: 2

Related Questions