Meteor data transfer from client to server

I have a registration form, and when the user clicks the submit button, the value in each text field is sent to the server to insert this data and returns true / false.

Client:

Template.cust_register.events({ 'click button': function(){ var email = $('#tbxCustEmail').val(); var msg = $('#tbxCustMsg').val(); var isSuccess = insertMsg(email,msg); if(isSuccess){ alert("Success"); }else alert("Try again"); } }); 

Server:

 function insertMsg(email,msg){ Messages.insert({Email:email,Message:msg}); return true; } 

It turned out to be inoperative. How to solve this? Many people said "use publication / subscription", but I don’t understand how to use it.

+3
javascript meteor
source share
2 answers

First, review the introductory screencast and read Data and Security in the docs.

Your code in the publish / subscribe model will look like this:

Are common:

 Messages = new Meteor.Collection('messages'); 

Client:

 Meteor.subscribe("messages"); Template.cust_register.events({ 'click button': function(){ var email = $('#tbxCustEmail').val(); var msg = $('#tbxCustMsg').val(); Messages.insert({Email:email,Message:msg}); } }); 

Server:

 Meteor.publish("messages", function() { return Messages.find(); }); 
+4
source share

An alternative solution is to use Meteor.call('yourMethodName') (on the client).

Then on the server you can have

 Meteor.methods({ yourMethodName: function() { /* validate input + return some data */ } }); 

You might consider setting a session variable to the return value.

 Meteor.call('yourMethodName', function (err, data) { if (!err) { Session.set('myData', data); } }); 

And then in some kind of template ...

 Template.whatever.helpers({ messages: function() { return Session.get('myData'); } }); 

Why all this?

 1) You can explicitly deny all direct `insert/update/find` queries from the client, and force usage of pre-defined Meteor methods. 2) You can manually determine when certain data is "refreshed". 

Obviously, this methodology undermines the value of the subscription / publication model and should only be used when real-time data is not required.

+4
source share

All Articles