Create a gist now

Instantly share code, notes, and snippets.

Meteor: Calling server method from client
<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>
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;
}
});
});
}
@muraiki
muraiki commented Mar 14, 2013

Thanks for posting this!

@m2web
m2web commented Dec 5, 2014

This was helpful.

@schen154
schen154 commented Jul 6, 2015

Nice!

@githubldd

Well done !

@seanfcarroll

+1

@thsowers

+1, very helpful

@jaykhimani

Thanks. Quite helpful

@RyuuZaky

Good, thanks 😄

@Innarticles

Thanks for this post. I want to call a method that returns a pre-filled html form to the client. please how can I do this?

@vojdan
vojdan commented Apr 29, 2016

Thank you 4 years later ;)

@AladinUsmilo

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment