Skip to content

Instantly share code, notes, and snippets.

@rootasjey
Created February 21, 2015 22:12
Show Gist options
  • Save rootasjey/421559aaeb9c6411ab87 to your computer and use it in GitHub Desktop.
Save rootasjey/421559aaeb9c6411ab87 to your computer and use it in GitHub Desktop.
How to send parameters to the server side in io.js (nodejs) with ajax
// This snippet demonstrates how to send a json object to the server
// and how to retrieve it from the server side to save it in a file
// CLIENT SIDE : PAGE.JS
// ---------------------
// Save stats to a file to retrieve values later
function saveToFile() {
var jsonArray = JSON.stringify(_stats);
console.log(jsonArray);
jsonArray = encodeURIComponent(jsonArray);
// Send an Ajax request to the server
// $.post('/counters/save', jsonArray, function (response) {
// console.log("totorr");
// });
var xhr = new XMLHttpRequest();
xhr.open('POST', '/counters/save?json=' + jsonArray, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(null);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log("Data correctly saved!");
}
}
}
// SERVER SIDE : SERVER.JS
// -----------------------
// Starts with the require to get modules
var express = require('express'), // web dev framework
jf = require('jsonfile'),
util = require('util');
// The app's configuration
app.use(bodyParser());
app.use(bodyParser.json()); // to suport JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to suport URL-encoded bodies
extended: true
}));
// Create an app object
// assuming you have node and express framework installed
var app = express();
// A POST url
app.post('/counters/save', function (req, res) {
// Save the values to a local file
// Set the path to save the file
var file = __dirname + '/public/modules/counters/data.json'; // enter your path
// Get the json object contained in the url
var obj = req.query.json;
// Write in the file
jf.writeFile(file, obj, function (err) {
console.log(err);
});
res.send(200);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment