3

I have a simple HTML form

index.html

<!DOCTYPE html>
<html>

    <head>
        <title>My Title</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script>
        function sendFormData(){
            var formData = JSON.stringify($("#myForm").serializeArray());

            $.ajax({
                type: "POST",
                url:"http://localhost:3000/test",
                data: formData,
                sucess: function(){
                    alert("something!");
                },
                error: function(textstatus, errorThrown) {
                    alert('text status ' + textstatus + ', err ' + errorThrown);
                }
            });
        } 
        </script>
    </head>

    <body> 
        <form id="myForm">
            Name: <input type="text" name="name">
            Address: <input type="text" name="address">
            <input type="submit" value="Submit" onClick="sendFormData()">
        </form>
    </body>
</html>

and I'm using Node.js to send the data to the server

server.js

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

// Express
var app = express();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

// Get information submitted
app.post('/test', function(req, res) {
    console.log("Information received !");
    console.log(req.body);
    res.send("Ok!");
});

// Start server
app.listen(3000);
console.log("API is running on port 3000");

I have two questions.

  1. Am I sending the extracted data from the form to the server correctly ? I can see the values in the console but the webpage keeps loading. I just wanted to send the data, display and alert and stay in the same page with the forms field cleaned.
  2. Should i validate the data (and how) from the form before or after sending the data to the server ? For instance, make sure no numbers are inserted in the field name or the field name should be less than 30 characters long.

UPDATE: I used Ajax instead of my initial approach to send the data to the server. I'm able to see the information sent with ajax in the console but the ajax success handler does not fire. I get this error XMLHttpRequest cannot load http://localhost:3000/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Thanks in advance !

Let_IT_roll
  • 389
  • 2
  • 6
  • 20

1 Answers1

2

Browser is waiting on the response from your server. Try:

app.post('/formdata', function(req, res) {
    console.log("You sent the name " + req.body.name + " and the address " + req.body.address);
    res.send("ok");
});

As for validation, usually you'd want to validate values both client side and server side. You can use something like this if you want to stick with express, or see here or here for a dual solution.

Update for the ajax thing:

You have a few errors in your code.

1) Typo in the 'success' hook (you typed 'sucess')

2) The way you call sendFormData() function, you both send ajax request and submit the form at the same time. Either intercept form submission, or change <input type="submit" into <input type="button" (so it doesn't trigger form submit)

As for the error, you can only send ajax to the same server that initially served the page (without some additional effort). This is called "same origin policy".

In your case, it looks like you're opening the page directly from disk using the 'file' protocol (url in the browser begins with file://). You need to have a real server serve your html, and then either set up 'same content origin' headers, or post back to the path on that same server (without the http://blabla... part).

The easiest thing you can do to get this to work is:

1) Let node serve your static content (index.html in this case)

app.use(bodyParser.json());
app.use(express.static('public'));

2) Move index.html into the 'public' directory, so that your file structure is:

- sever.js
- [public]
    |- index.html

3) Remove hardcoded url from your requests

$.ajax({
    type: "POST",
    url:"/test",
    data: formData,
    //...
});

4) Open http://localhost:3000/ in your browser

Community
  • 1
  • 1
panta82
  • 2,763
  • 3
  • 20
  • 38
  • By using "res.send("ok") I end up in a different page. The infinite loading stops but I would like to stay on the same page. Is it possible ? – Let_IT_roll Apr 01 '15 at 22:36
  • Once you post form, you've already left the page. You can only render a new page in return. To stay on the same page, look into using ajax instead of posting the form. – panta82 Apr 01 '15 at 22:42
  • So, instead of using the form `method` and `action` you are suggesting to create and ajax request using for instance the `onClick` handler ? How can I handle the information then ? I started using Node.js today and the things are still a little bit confusing :) – Let_IT_roll Apr 01 '15 at 23:16
  • This is purely a browser issue. Your node.js code will remain the same. See here how to send the form through AJAX instead of posting it: http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form (yes, definitely add jQuery to your frontend) – panta82 Apr 01 '15 at 23:32
  • I think I'm starting to get the thing less mixed up :) Please check my update. I'm able to send the data using ajax to the server, print it but the ajax success handler does not fire. Instead, i get an error. – Let_IT_roll Apr 02 '15 at 00:47
  • Updated. This is now very off topic, you should probably post another question if you have more problems. – panta82 Apr 02 '15 at 06:37
  • Thanks ! It did work. I'm going to follow your suggestion and if I have more problems i'll post a new question. – Let_IT_roll Apr 02 '15 at 19:24