I have a simple HTML form
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Title</title>
<script src="http://ift.tt/1yCEpkO"></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.
- 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.
- 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 !
Aucun commentaire:
Enregistrer un commentaire