AbtPst
AbtPst

Reputation: 8018

NodeJS : How to have multiple methods for post

i am trying to make an iteractive form using nodejs.

Here is my web page

<!DOCTYPE html>
 <html>
 <script>
     $('#ping-button').click(function() {
        $.ajax({
            type: 'POST',
            url: 'http://localhost:3000/process_test'
        });
    });
 </script>
    <body>
        <form action="http://127.0.0.1:3000/process_get" method="GET">
        First Name: <input type="text" name="first_name">  <br>

        Last Name: <input type="text" name="last_name">
        <input type="submit" value="Submit">
        </form>
        <br>
        <form action="http://127.0.0.1:3000/process_post" method="POST">
        Team: <input type="text" name="team">  <br>

        Player: <input type="text" name="player">
        <input type="submit" value="Submit">

        <br><br>

        <button id='ping-button'>Ping</button>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

        </form>
    </body>
</html>

and here is my app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('test'));

app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})

app.get('/process_get', function (req, res) {

   // Prepare output in JSON format
   response = {
       first_name:req.query.first_name,
       last_name:req.query.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));
})

app.post('/process_test', urlencodedParser, function (req, res) {


   console.log("Ping");
   res.end(JSON.stringify("Ping"));
})

app.post('/process_post', urlencodedParser, function (req, res) {

   // Prepare output in JSON format
   response = {
       team:req.body.team,
       player:req.body.player
   };
   console.log(response);
   res.end(JSON.stringify(response));
})



var server = app.listen(3000, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)

})

so i have two forms and a button. The first form is tied to the process_get method, the second form is tied to the process_post method and the button is tied to the process_test method.

both of the forms give expected results. When i click the button, it goes to the process_post method instead of the process_test

why does this happen?

Upvotes: 0

Views: 790

Answers (1)

vesse
vesse

Reputation: 5078

The reason the Ping button submits the form to /process_post is because it is inside the form, and the click handler is not set due to errors.

If you open the console in your browser you will see Uncaught ReferenceError: $ is not defined. This is because you're using $ in your code, but you include jQuery much later in the page. This you can fix by loading jQuery prior to your script tag.

Once that is done you will notice that the button still does not work. This is because the script inside head is executed before the rest of the document is done, ie. the body contents is not there yet, and $('#ping_button') will find nothing. This you fix by wrapping you code inside $(document).ready(function() { // code here }); so it is executed once the whole page is loaded.

Still, clicking the button will send you to /process_post because the click event is not stopped in your click handler. Return false or use e.preventDefault() to disable the browser default action.

All this combined the head section (that was missing) will become

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
    $(document).ready(function() {
        $('#ping-button').click(function(e) {
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'http://localhost:3000/process_test'
            });
            return false;
        });
    }); 
    </script>
</head>
<body>
<!-- Rest of your page -->
</body>
</html>

Upvotes: 2

Related Questions