Transfer data via AJAX to NodeJS


  • NodeJS with Express

Client-Side Code

I’m using a jQuery UI DatePicker as an example. But it can be transferred to any other element for doing an AJAX-Call.

$(document).ready(function() {
	$('#datepicker').datepicker( { 
		onSelect: function(date, pickerInstance){ 
				url: '/datepicker',
				data: {'date':date},
				type: 'POST'
	} );

Server-Side Code

This code is running on NodeJS.

var app = express()
app.use(express.bodyParser()); // must be before any 'app.use(express.static(__dirname + '/public'))'-statements

...'/datepicker', function(request, response){
  console.log(request.body)       // your JSON
  response.send(request.body);    // echo the result back

It is important to have app.use(express.bodyParser());, which is used for JSON parsing, in the very beginning of the server code. Any routing stuff like app.use(express.static(__dirname + '/public')) must be set afterwards, otherwise the request.body will be undefined.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.