I am new to meteor, but it seems like this should be simple. I want to create a page that pulls a get variable down and displays it on the client
ex: www.example.com?yourname=bob
and the page would display
bob
I feel like this should be easy, but so far have not been able to do it. I created an call when the client loads that asks for the info, but it doesn't work on the first load for some reason. On subsequent loads it does.
<head>
<title>Page Chat</title>
</head>
<body>
<div id="wrapper">
{{> name}}
</div>
</body>
<template name="name">
{{name}}
<br />
<input type="button" value="Click" />
</template>
js code
if (Meteor.isClient) {
Meteor.startup(function(){
Meteor.call("getData", function(error, result){
if(error){
Session.set("name", "bob");
}
else{
Session.set("name", result.name);
}
});
});
Template.name.name = function(){
return Session.get("name");
};
Template.name.events({
'click input' : function () {
// template data, if any, is available in 'this'
if (typeof console !== 'undefined')
console.log("You pressed the button");
}
});
}
if (Meteor.isServer) {
var connect = Npm.require('connect');
var app = __meteor_bootstrap__.app;
var post, get;
app
// parse the POST data
.use(connect.bodyParser())
// parse the GET data
.use(connect.query())
// intercept data and send continue
.use(function(req, res, next) {
post = req.body;
get = req.query;
return next();
});
Meteor.startup(function () {
});
Meteor.methods({
getData: function() {
return get;
},
postData: function(){
return post;
}
});
}
If possible I would like to share the data on the initial page load, it seems like a waste to create an separate page load to get information thats already there when the page is first loading.
It might be easier to use something like meteor-router. Then you could do
server side js:
Meteor.Router.add('/something', function() {
return this.params.yourname;
});
So if you visited example.com/something?yourname=Bob you would get back Bob.
Be careful when displaying something directly to the client from a querystring/input parameter as if you don't check it before it could be used for XSS.
Original url is "http://example.com:3000/test?xyz", you can use any one below
Router.current().request.url
"http://example.com:3000/test?xyz"
Router.current().url
"http://example.com:3000/test?xyz"
Router.current().originalUrl
"http://example.com:3000/test?xyz"
Router.current().route._path
"/test"
Router.current().route.getName()
"test"
https://github.com/iron-meteor/iron-router/issues/289
Related
//Client side code in client\main.js
Tasks=new Mongo.Collection('tasks');
Template.tasks.helpers({
tasks:function () {
return Tasks.find({},{sort:{createdAt:-1}});
}
});
Template.tasks.events({
"submit .add-task":function (event) {
var name = event.target.name.value;
Meteor.call('addTask',name);
event.target.name.value='';
return false;
},
"click .delete-task":function (event) {
if(confirm('Delete Task?')){
Meteor.call('deleteTask',this._id);
}
return false;
}
});
Meteor.methods({
addTask: function (name) {
if (!Meteor.userId()) {
throw new Meteor.Error('No Access!!');
}
Tasks.insert({
name: name,
createdAt: new Date(),
userId: Meteor.userId()
});
},
deleteTask: function(taskId) {
Tasks.remove(taskId);
}
});
//Server side code in server\main.js
Tasks=new Mongo.Collection('tasks');
Meteor.methods({
addTask: function (name) {
if (!Meteor.userId()) {
throw new Meteor.Error('No Access!!');
}
Tasks.insert({
name: name,
createdAt: new Date(),
userId: Meteor.userId()
});
},
deleteTask: function taskId() {
Tasks.remove(taskId);
}
});
//Html page
<head>
<title>tasklist</title>
</head>
<body>
{{> tasks}}
</body>
<template name="tasks">
{{> loginButtons}}
<h1>Add Task</h1>
{{#if currentUser}}
<form class="add-task">
<label>Task Name</label>
<input type="text" name="name" placeholder="Add Task" />
<input type="submit" value="Submit" />
</form>
{{else}}
<p>Please log in to add tasks</p>
{{/if}}
<hr />
<h3>Tasks</h3>
<ul>
{{#each tasks}}
<li>{{name}}{{#if currentUser}} X{{/if}} </li>
{{/each}}
</ul>
</template>
Please help, in this when i reload page it first add and and shows in the web-page and if i delete the try todelete the added then screen doesnot show even added tasks which are in MongoDB.
And when i do console, there is an empty array of added tasks
If it "blinks" this often means that your Method worked client side but not server side. The insert worked on your Minimongo (client) but not on the real MongoDB (server). So Meteor decide to rollback your insert on Minimongo.
You must have a problem inside your Method server side:
You can't use Meteor.userId() server side in your Methods, you have to use this.userId.
To avoid mistakes, only use this.userId inside the Meteor Methods client or server side.
// Server side
Meteor.methods({
addTask: function (name) {
if (!this.userId) {
throw new Meteor.Error('No Access!!');
}
Tasks.insert({
name: name,
createdAt: new Date(),
userId: this.userId
});
},
deleteTask: function taskId() {
Tasks.remove(taskId);
}
});
In Meteor, you don't have to duplicate your Methods client AND server side.
Methods should always be defined in common code loaded on the client and the server to enable Optimistic UI.
You just have to define your Methods and your collection one time inside a folder loaded on client and server. For exemple you can put your code inside a folder named both/.
I have called actionresult function from JavaScript using AJAX when a button is clicked:
<script type="text/javascript">
$('.btn-SelectStudent').on('click', function () {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var id = $(this).val();
$.ajax({
url: '#Url.Action("ParseSearchLists", "Upload")',
data: { studentId: id }
}).success(function (data) {
alert('success');
});
}
else {
// Or an unchecked one here...
}
});
return false;
})
</script>
Inside the UploadController.cs:
[HttpPost]
public ActionResult ParseSearchLists(int studentId)
{
SearchModel searchModel = ApplicationVariables.searchResults.Where(x => x.StudentId == studentId).ToList().First();
TempData["SearchModel"] = searchModel;
return RedirectToAction("UploadFile", "Upload");
}
public ActionResult UploadFile()
{
searchModel = TempData["SearchModel"] as SearchModel;
return View(searchModel); //debug point hits here.
}
Inside UploadFile(), I have returned View and it should load another view. But I get only "success" in alert but no new view is loaded. I assume, view should be loaded.
You're making an "AJAX" call to the server, meaning your request is running outside of the current page request and the results will be returned to your success continuation routine, not to the browser's rendering engine. Essentially the data parameter of that routine is probably the entire HTML response of your UploadFile view.
This is not what .ajax is used for. It is for making asynchronous requests to the server and returning data (usually JSON or XML) to your javascript to be evaluated and displayed on the page (this is the most common use anyway).
I can't see your HTML, but wouldn't you be better off just using an <a> anchor (link) tag and sending your student ID on the query string? It's hard to tell what you are attempting to do but your views' HTML (.cshtml) will never be displayed using the code you have now.
It seems, you are not loading view returned to div on ajax success. replace #divname with your div in your code in below code. i hope this helps to resolve your issue
<script type="text/javascript">
$('.btn-SelectStudent').on('click', function () {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var id = $(this).val();
$.ajax({
url: '#Url.Action("ParseSearchLists", "Upload")',
dataType: "html",
data: { studentId: id }
}).success(function (data) {
$('#divName').html(data); // note replace divname with your actual divname
});
}
else {
// Or an unchecked one here...
}
});
return false;
})
</script>
[HttpPost]
public ActionResult ParseSearchLists(int studentId)
{
SearchModel searchModel = ApplicationVariables.searchResults.Where(x => x.StudentId == studentId).ToList().First();
return View("UploadFile",searchModel); //debug point hits here.
}
Why isn't this reactive? And more importantly how can it be made reactive?
I'd like the data to be saved in Mongo and used in the template. I could use a ReactiveVar or ReactiveDict. Do I need two copies of the data?
Doesn't Suspects.findOne('bruce') return a reactive object already? I tried putting the human answer directly on Bruce, but it didn't trigger an update.
The events fire, log(this) shows bruce's answer was changed, but the template doesn't re-render. What's the good way to do this?
http://meteorpad.com/pad/KoH5Qu7Fg3osMQ79e/Classification
It's Meteor 1.2 with iron:router added:
<head>
<title>test</title>
</head>
<template name="question">
{{#unless isAnswered 'human'}} <!-- :-< I'm not reacting here -->
<div>Sir, are you classified as human?</div>
<button id="no">No, I am a meat popsicle</button>
<button id="smokeYou">Smoke you</button>
{{else}}
<div> Classified as human? <b>{{answers.human}}</b></div>
{{/unless}}
</template>
And the JavaScript:
// Why isn't this reactive?
if (Meteor.isClient) {
Template.question.helpers({
isAnswered: function (question) { // :-< I'm not reactive
var suspect = Template.instance().data;
return (typeof suspect.answers[question] !== 'undefined');
}
});
Template.question.events({
'click #no': function () {
this.answers.human = "No"; // :-< I'm not reactive
console.log(this);
},
'click #smokeYou': function() {
this.answers.human = "Ouch"; // :-< I'm not reactive
console.log(this);
}
});
}
// Collection
Suspects = new Meteor.Collection('suspects');
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
Suspects.upsert('bruce', { quest: 'for some elements', answers: {}});
});
Meteor.publish('suspects', function() {
return Suspects.find({});
});
}
// Iron Router
Router.route('/', {
template: 'question',
waitOn: function() {
return Meteor.subscribe('suspects');
},
data: function() {
return Suspects.findOne('bruce');
}
});
Thanks :-)
The events are not actually updating the reactive data source (the db record). Instead of doing:
Template.question.events({
'click #no': function () {
this.answers.human = "No";
}
});
The event needs to perform a database action, either through a direct update or through a Meteor.call() to a Meteor.method. For example:
'click #no': function(){
Suspects.update('bruce', {'answers': {'human': 'no'}});
}
If you use this pattern, you will also need to set the correct allow and deny rules to permit the update from client code. http://docs.meteor.com/#/full/allow. Methods generally end up being a better pattern for bigger projects.
Also, I'm not sure off the top of my head that Template.instance().data in your helper is going to be reactive. I would use Template.currentData() instead just to be sure. http://docs.meteor.com/#/full/template_currentdata
Very close you just need to use ReactiveVar by the sound of it it pretty much explains what it's :) http://docs.meteor.com/#/full/reactivevar
and here's how to use it
if (Meteor.isClient) {
Template.question.onCreated(function () {
this.human = new ReactiveVar();
});
Template.question.helpers({
isAnswered: function (question) {
return Template.instance().human.get();
}
});
Template.question.events({
'click #no': function (e, t) {
t.human.set('No');
console.log(t.human.get());
},
'click #smokeYou': function(e, t) {
t.human.set('Ouch');
console.log(t.human.get());
}
});
}
UPDATE: if you're using a cursor I usually like to keep it on the template level not on iron router:
if (Meteor.isClient) {
Template.question.helpers({
isAnswered: function (question) {
return Suspects.findOne('bruce');
}
});
Template.question.events({
'click #no': function (e, t) {
Suspects.update({_id: ''}, {$set: {human: 'No'}});
},
'click #smokeYou': function(e, t) {
Suspects.update({_id: ''}, {$set: {human: 'Ouch'}});
}
});
}
I am trying to submit an image.. and I've been at this for the past two days. It seems like it's super simple but I can't get it the way I want it to.
In the examples for collectionFS (and every other example I can find), they use an event that's called 'change'. https://github.com/CollectionFS/Meteor-CollectionFS
This event will update and save the file everytime the user wants to upload an image (or any file). They don't have to press "submit" to save it.
Is this the correct way to do things? I am trying to change it so I can blend event into my 'submit form' event, but it doesn't seem to work.
'submit form': function(event, template) {
console.log('this logs')
FS.Utility.eachFile(event, function(file) {
console.log('this doesnt log');
Images.insert(file, function(err, fileObj) {
if (err) {
// handle error
} else {
// handle success depending what you need to do
var userId = Meteor.userId();
var imagesURL = {
"profile.image": "/cfs/files/images/" + fileObj._id
};
Meteor.users.update(userId, {
$set: imagesURL
});
}
});
});
}
However, this doesn't seem to save the file. It doesn't even run the FS.Utility.eachFile part. I've tried all sorts of variations, but if I listed them all I'm afraid it would make a terribly long post. I thought perhaps someone could point me to the right direction? I've tried saving the file into a variable and then inserting them... but I can't seem to get FS.Utility to run with a submit form.
Any help would be much appreciated!
For those who struggle with this later, it's an issue with the assumptions the package makes at the present (1-5-2015). In cfs_base-packages.js:
FS.Utility.eachFile = function(e, f) {
var evt = (e.originalEvent || e);
var files = evt.target.files;
if (!files || files.length === 0) {
files = evt.dataTransfer ? evt.dataTransfer.files : [];
}
for (var i = 0; i < files.length; i++) {
f(files[i], i);
}
};
It's looking for a your event to be structured like this: event.originalEvent.target.files, however the event triggered by submit is originalEvent.target: "" So a dirty work-around would be to do something like this:
Template.templateName.events({
'submit .myForumClass': function(event, template) {
event.preventDefault();
event.originalEvent.target = {};
event.originalEvent.target.files = event.currentTarget[0].files;
//0 is the position of the input field in the parent form
FS.Utility.eachFile(event, function(file) {
Images.insert(file, function (err, fileObj) {
//stuff
});
});
},
});
Hope the below example helps.
<template name="fileupload">
<form class="form-horizontal" role="form">
<input type="file" name="...">
<button type="submit" value="Update" class="btn btn-primary">Upload File</button>
</form>
</template>
Template.fileupload.events({
'submit form': function (event, template) {
console.log("Submit form called");
event.preventDefault();
var fileObj = template.find('input:file');
FilesCollection.insert(fileObj.files[0], function (err, fileObj) {
});
}
});
I am not able to pass data from server block to client block . I am also not sure the way I call self created package is right or wrong .
Here is my folder structure :
x/packages/me.js
x/packages/package.js
x/packages/smart.json
x/x.css
x/x.html
x/x.js
Here is all code :
me.js
Meteor.methods({
getTweets: function () {
var key = "my api key";
var response = Meteor.http.call( "POST", "http://localhost:8000/users.json",
{ params: { appkey: key ,uid: "example" }});
return response.content;
}
});
package.js
Package.describe({
summary: "summary etc"
});
Package.on_use(function (api){
api.use(["http"],["server"]);
api.add_files("me.js","server");
});
smart.json
{
"name": "name example",
"description": "desc",
"homepage":"as",
"author" : "xyz",
"version" : "0.1",
"packages": {}
}
x.html
<head>
<title>x</title>
</head>
<body>
{{> hello}}
</body>
<template name="hello">
<h1>Hello World!</h1>
{{greeting}}
<input type="button" value="Click" />
</template>
x.js
if (Meteor.isClient) {
Template.hello.greeting = function () {
return "Welcome to y.";
};
Template.hello.events({
'click input' : function () {
// template data, if any, is available in 'this'
Meteor.call("hiren",function (err, data) {
console.log(data);
if(err) throw err;
});
}
});
}
if (Meteor.isServer) {
Meteor.call("getTweets",function (err, data) {
Meteor.methods({
"hiren":function(){
return data;
}
});
});
}
When I click the "click" button , it just shows undefined
One problem is here:
if (Meteor.isServer) {
Meteor.call("getTweets",function (err, data) {
Meteor.methods({
"hiren": function(){
return data;
},
});
});
}
You define your methods inside a callback function of getTweets method. This is probably not what you want to do, usually those are defined right in the server block as you want to have a predictable API. I cannot think of a reason to do such thing as you did, but even if there is one - you didn't call the getTweets function. So I guess it's a mistake.