public
Last active

Meteor: Calling server method from client

  • Download Gist
meteor_servercall.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<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>
meteor_servercall.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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;
}
});
});
}

Thanks for posting this!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.