Meteor: Calling server method from client
if (Meteor.is_client) {
Template.simple.result = function () {
return Session.get('serverSimpleResponse') || "";
};
Template.simple.events = {
'click input' : function () {
Meteor.call('getCurrentTime',function(err, response) {
Session.set('serverSimpleResponse', response);
});
}
};
Template.passData.result = function () {
return Session.get('serverDataResponse') || "";
};
Template.passData.events = {
'click input[type=button]' : function () {
Meteor.call('welcome', $('input[type=text]').val(), function(err,response) {
if(err) {
Session.set('serverDataResponse', "Error:" + err.reason);
return;
}
Session.set('serverDataResponse', response);
});
}
};
}
if (Meteor.is_server) {
Meteor.startup(function () {
Meteor.methods({
getCurrentTime: function () {
console.log('on server, getCurrentTime called');
return new Date();
},
welcome: function (name) {
console.log('on server, welcome called with name: ', name);
if(name==undefined || name.length<=0) {
throw new Meteor.Error(404, "Please enter your name");
}
return "Welcome " + name;
}
});
});
}
<head>
<title>meteor_servercall</title>
</head>
<body>
{{> simple}}
{{> passData}}
</body>
<template name="simple">
<h1>Calling serve method</h1>
<input type="button" value="Call" />
<div id="simpleResult">{{result}}</div>
</template>
<template name="passData">
<h1>passing data to server method</h1>
<span>Name: </span><input type="text" value="Nachiket"/>
<input type="button" value="Call" />
<div id="passDataResult">{{result}}</div>
</template>