how to use a remote back-end to check if a given username is already taken or not.
check and validate locally without using database or web-server
This is latest version of bootstrapValidator, jquery, html5, bootstrap.
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/js/bootstrapValidator.min.js"></script>
<form id="registrationForm" class="form-horizontal">
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="username" />
</div>
</div>
</form>
and custom js is
$(document).ready(function() {
$('#registrationForm').bootstrapValidator({
fields: {
username: {
message: 'The username is not valid',
validators: {
remote: {
message: 'The username is not available',
url: 'default.php',
data: {
type: 'username'
}
}
}
}
}
});
});
back-end default.php file is
<?php
$isAvailable = true;
switch ($_POST['type']) {
case 'username':
default:
$username = $_POST['username'];
data = 'admin','root';
$isAvailable = true;
break;
}
echo json_encode(array(
'valid' => $isAvailable,
));
username already exists or not from default.php file, error
not showing.
$(document).ready(function() {
$('#registrationForm').bootstrapValidator({
fields: {
username: {
message: 'The username is not valid',
validators: {
callback: {
callback: function(value, validator) {
var data = "user1";
if (value === data) {
return {
valid: false,
message: 'The name is not available'
}
}
return true;
}
}
}
}
}
});
});
Instead of using php function, I have used call back function for this it's working fine.
Related
Using jQuery validation plugin, I have been trying to validate and submit my form. JS code for this as shown below.
jQuery.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Enter a valid phone number."
);
var phoneNumbers_default = {
maxlength: 11,
regex: /^0+\d{2}[ -]\d{7}( x\d{1,6})?$/,
remote: "./includes/check-duplicate-mobile.php"
// remote: {
// url: "./includes/check-duplicate-mobile.inc.php",
// type: "post"
// }
};
var phoneNumbers_required = {
required: true
};
var phoneNumber_message = {
minlength: "Your mobile number should be at least 11 digits long.",
maxlength: "Your mobile number cannot be longer than 11 digits.",
remote: "One active user account already exists for this mobile number. Duplicates are not allowed."
}
jQuery.extend(phoneNumbers_default,phoneNumbers_required);
function processForms(el,fileAttached=false) {
var $el = $('#'+el)
$el.validate({
errorElement: 'span',
focusInvalid: false,
//ignore: ".ignore",
ignore: "",
rules: {
email: {
required: true,
email: true
},
mobileNumber: phoneNumbers_default,
p_mobile: phoneNumbers_default,
},
messages: {
email: {
required: "Please provide a valid email.",
email: "Please provide a valid email."
},
mobileNumber:phoneNumber_message,
p_mobile:phoneNumber_message,
},
submitHandler: function (form) {
var $form = $(form);
var url = 'add_user_form.php';
var formData = new FormData(form);
$.ajax({
url: url,
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(json) {
json = jQuery.parseJSON(json)
if (json.success) {
// it worked
} else {
// it not worked
}
},
});
return false;
}
})
}
Above code works fine for the first submit. I meant it is new form submission. But my problem is when I try to update the existing data using the same form it always checks remote method and become return ture. That means, if I want to update the existing data, I always have to change the mobile number.
UPDATE:
Form markup
<form class="mt-2 text-dark-m1" id="addNew_user" method="post" action="" >
<div class="form-group row">
<div class="col-sm-3 col-form-label text-sm-right pr-0">
Email:
</div>
<div class="col-sm-9">
<input type="text" name="principal_email" class="form-control col-sm-4" value="<?=$p_email?>" />
</div>
</div>
<div class="form-group required row">
<div class="col-sm-3 col-form-label text-sm-right pr-0">
Mobile :
</div>
<div class="col-sm-9">
<input type="text" name="p_mobile" class="form-control col-sm-4" value="<?=$p_mobile?>" required />
</div>
</div>
<div class="border-t-1 bgc-secondary-l4 brc-secondary-l2 py-35 mx-n25 mt-5">
<div class="offset-md-3 col-md-9 text-nowrap flex-align-center">
<button class="btn btn-info btn-bold px-4" type="submit"><i class="fa fa-check mr-1"></i>Submit</button>
</div>
</div>
</form>
Serverside Code:
$mobileNumber = isset($_GET['p_mobile']) ? $_GET['p_mobile'] : '';
if (strlen($mobileNumber) >= 10 && strlen($mobileNumber) <= 12) {
$sql ="SELECT user_id FROM user WHERE mobile = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$mobileNumber]);
$uid = $stmt->fetchColumn();
if ($uid) echo "false"; // it comes to this line
else echo "true";
} else {
echo "false";
}
Can anybody tell me, how I fix this issue?
What about making this change in the server side? I am still learning php, but i believe you will get the idea.
$mobileNumber = isset($_GET['p_mobile']) ? $_GET['p_mobile'] : '';
$requestUserId = isset($_GET['user_id']) ? $_GET['user_id'] : '';
if (strlen($mobileNumber) >= 10 && strlen($mobileNumber) <= 12) {
$sql ="SELECT user_id FROM user WHERE mobile = ?";
if (requestUserId) $sql += " AND user_id <> ?"
$stmt = $pdo->prepare($sql);
$stmt->execute([$mobileNumber, $requestUserId]);
$uid = $stmt->fetchColumn();
if ($uid) echo "false"; // it comes to this line
else echo "true";
} else {
echo "false";
}
I have a register form which works with Vue and local storage, when I submit the form blank or leave out an input the data is going to the local storage the same and not showing the HTML validation which is used by adding required attribute. Is there any way I can fix this problem by showing the HTML validation if the form has inputs which are empty or if the email do not have an at-sign inserted.
Form:
<form id="signup" method="post" v-on:submit.prevent>
<br>
<h1>Registration</h1>
<label for ="studentsorparents">Student or parents:</label>
<input type="text" id="studentsorparents" v-model="studentsorparents" required ="required">
<br><br>
<label for ="username">username:</label>
<input type="text" id="username" v-model="username" required ="required" v-text="null">
<br><br>
<label for="email">email: </label>
<input type="email" id="email" v-model='email' required ="required">
<br><br>
<label for="password">password: </label>
<input type="password" id="password" v-model='password' required ="required">
<br><br>
<button v-on:click='onSubmit' onclick="passuseremail()" >Register</button>
</form>
JS:
var signupApp = new Vue({
el: '#signup',
data: {
studentsorparents: '',
username: '',
email: '',
password: '',
},
methods: {
onSubmit: function () {
// check if the email already exists
var users = '';
var studentParent = this.studentsorparents;
var newUser = this.username;
var newEmail = this.email;
if (localStorage.getItem('users')) { // 'users' is an array of objects
users = JSON.parse(localStorage.getItem('users'));
}
if (users) {
if (users.some(function (user) {
return user.username === newUser
})) {
alert('Account already exits');
return;
}
if (users) {
if (users.some(function (user) {
return user.email === newEmail
})) {
alert('Account already exits');
return;
} else {
alert('Account created');
window.location.href = 'user-profile.html' + '#' + newUser;
}
}
users.push({
'studentsorparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
});
localStorage.setItem('users', JSON.stringify(users));
} else {
users = [{
'studentparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
}];
localStorage.setItem('users', JSON.stringify(users));
}
}
}
});
function passuseremail()
{
var username = document.getElementById('username').value;
localStorage.setItem("user-check", username);
var studentsorparents=document.getElementById('studentsorparents').value;
localStorage.setItem("students-parents-check", studentsorparents)
var email=document.getElementById('email').value;
localStorage.setItem("email-check", email)
return false
}
You need to add button type='submit' to the submit button else it will behave like just any other button.
<button v-on:click='onSubmit' onclick="passuseremail()" type="submit">Register</button>
It then only act as submit button else it will just trigger the button eventlisteners attached.
You have spaces after required attributes in your inputs:
required ="required"
It's incorrect and it will not work; just write it like this:
<input type=email id=email v-model=email required>
You can validate email like this:
const email_re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
if (email_re.test( email.value )) {
/* email is valid */
} else {
/* email is not valid */
}
You can add a class to the button like jsValidateRegister.
And the add the code
First declare a variable
isPageValid = true
Then in add the following code for validation so the isPageValid is set to false inside the passuseremail();
$(".jsValidateRegister").click(function ()
{
passuseremail();
});
In the onSubmit: function () check
isPageValid === true
I make a web form to add some string to database and now my add function is running perfectly but my web does not send params to function when i click submit and console log send undefined to me i dont know what to do please help and thank you
Here my function code and run perfectly
Parse.Cloud.define('addSynonym', function (request, response) {
var SYN = Parse.Object.extend("Synonym");
var CommonwordFromUser = request.params.common_word;
var SynonymwordFromUser = request.params.synonym_word;
console.log(CommonwordFromUser);
console.log(SynonymwordFromUser);
if (CommonwordFromUser == null || SynonymwordFromUser == null) {
response.error("request null values");
} else {
var query = new Parse.Query(SYN)
query.find({
success: function (synResponse) {
var synOBJ = new SYN();
synOBJ.set("common_word", CommonwordFromUser);
synOBJ.set("synonym_word", SynonymwordFromUser);
synOBJ.save(null, {
success: function (success) {
response.success({
"common_word": CommonwordFromUser,
"synonym_word": SynonymwordFromUser
});
},
error: function (error) {
response.error("save failed : " + error.code);
}
});
}
})
}
});
Here my web form my problem
<form id="contact" class="registerForm">
<div class="alert alert-success" id="alertbox">
<strong>Success!</strong> Your Synonym has uploaded.
</div>
<div class="text-center">
<img src="img/icon.png" class="text-center" alt="Responsive image" width="90" height="90">
</div>
<h3 class="text-center font-weight-normal">Welcome to synonym Menu</h3>
<label id="label-tags" for="ask-tags">Common Word :</label>
<fieldset class="form-group">
<input id="common_word" name="common_word" placeholder="Please type some word" type="text" tabindex="1" required>
</fieldset>
<label id="label-tags" for="ask-tags">Synonym Word :</label>
<fieldset class="form-group">
<input id="synonym_word" name="synonym_word" placeholder="Please type some word" type="text" tabindex="2"
required>
</fieldset>
<fieldset class="form-group">
<button name="submit" type="submit" onclick="submitfrom()" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script src="js/standalone/selectize.min.js"></script>
<script src="js/bootstrapValidator.min.js"></script>
<script>
$('.registerForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
common_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
synonym_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
}
}).on('success.form.bv', function (e) {
submitfrom();
});
$('#alertbox').hide();
function submitfrom() {
var common_word = $('#common_word').val();
var synonym_word = $('#synonym_word').val();
var obj = [{
"common_word": common_word,
"synonym_word": synonym_word,
}];
var data = '{"objects":' + JSON.stringify(obj) + '}';
callParseServerCloudCode("addSynonym", data, function (response) {
if (response) {
console.log(response);
alert("🤖:Ok !");
location.reload();
}
});
$(this).scrollTop(0);
$('.registerForm').data('bootstrapValidator').resetForm();
$('#alertbox').show();
$('#alertbox').fadeTo(2000, 500).slideUp(500, function () {
$('#alertbox').hide();
});
}
function callParseServerCloudCode(methodName, requestMsg, responseMsg) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://xxxxxxxxxxxx.herokuapp.com/parse/functions/' + methodName, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('X-Parse-Application-Id', 'myAppId');
xhr.setRequestHeader('X-Parse-Master-Key', 'myMasterKey');
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
responseMsg(myArr.result);
}
};
xhr.send(requestMsg);
}
</script>
</body>
</html>
Option 1:
Just change the lines below and it should work
var obj = {
"common_word": common_word,
"synonym_word": synonym_word,
};
var data = JSON.stringify(obj);
Option 2 (recommended):
Install Parse JS SDK: https://docs.parseplatform.org/js/guide/#getting-started
Call cloud code like this:
Parse.Cloud.run(
"addSynonym",
{
"common_word": common_word,
"synonym_word": synonym_word
}
).then(
function() {
console.log('success');
},
function (error) {
console.error(error);
}
);
I followed an example, http://formvalidation.io/examples/using-data-returned-validator/, and was able to implement simple validation for email and usernames. I found another demo/example which uses ajax to call a live email checker php script.
What I have not figured out is how to implement (combine) the live username checker with the standard validator so that it both checks to see if the email is of a valid format in addition to be available to use, not a registered member already. Messing with the javascript, I have gotten the validator to see my php script, check_email.php using an AJAX post.
However I don't have the right syntax to make the validator make use of the result of the php script to return a message like 'Duplicate" or "Email in use". The html for the email:
<!-- EMAIL -->
<div class="form-group">
<div class="row">
<label class="col-xs-6 control-label">Email address</label>
<div class="col-xs-6" style='clear:left;width: 50%;'>
<input type="text" class="form-control email" name="email" />
</div>
</div>
</div>
The relevant part of the javascript:
<script>
$(document).ready(function() {
$('#taskForm').formValidation({
framework: 'bootstrap',
icon: {
// required: 'fa fa-asterisk',
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
'email': {
validators: {
notEmpty: {
message: 'The email address is required'
},
emailAddress: {
message: 'The input is not a valid email address'
}
,
remote: {
type: 'POST',
url: 'check_email.php',
message: 'Duplicate or whatever ...',
cache: false,
success: function(result){
var result=remove_whitespaces(result);
if(result=='')
{
// Do something ...
}
}
}
}
},
}
})
});
</script>
To see the demo form visit http://dottedi.us/validation/validator.php. To illustrate that the live checker works use the username of 'sowhat' and email address of 'sowhat#dottedi.biz' to test. I have the username working separately with a username checker just to show that it works, not the desired method. Email is currently broken with my code.
I can modify check_email.php if necessary. Currently it returns $HTML='email exists'; if is a duplicate.
The question: how do I change the structure, syntax of the remote function so that it can make use of a response from check_email.php?
Oh, and here is the php code in check_email.php:
<?php
include ("mysql_connection.php");
$HTML = "";
if(isset($_POST['email']) && !empty($_POST['email']))
{
$email=strtolower(mysql_real_escape_string($_POST['email']));
$query="select * from members where LOWER(email)='$email'";
$res=mysql_query($query);
$count=mysql_num_rows($res);
if($count > 0){ $HTML='email exists'; }else{ $HTML=''; }
}
echo $HTML;
?>
I kept digging and found the answer at: http://formvalidation.io/validators/remote/
1) Changed the relevant javascript to:
remote: {
message: 'This email address is taken',
url: 'check_email.php',
type: 'POST'
}
2) Changed check_email.php to return JSON format response:
if ( $count > 0 ) { $status = false; } else { $status = true; }
if(isset($status))
{
$data = array(
"valid" => $status,
"email" => $email // OPTIONAL
);
echo json_encode($data);
}
trying to debug something. On our client, we have a Accounts.createUser() call, which include a callback that looks like:
function(err) {
if (err) {
Session.set('entryError', err.reason);
}
else {
return Router.go('/');
}
}
With this setup, a normal signup (i.e. with no errors) works fine. However, if there's an error, the template is destroyed, created, and rendered, twice. I found this question, and went on a hunt for potential reactive variables triggering this. The only thing I can find that changes between the two template destroyed/created/rendered calls is Meteor.loggingIn() (including session variables). That doesn't seem to be causing this, because when I removed all references to it and dependencies on it, the problem continued.
Any pointers?
ETA: per the request below.
signUpPage.html:
<template name='signUpPage'>
<main id="signUpPage">
<h1 class="accountsTitle">Sign Up</h1>
<p id="signInPrompt">If you already have an account sign in.</p>
<form id='signUpForm'>
{{> entryError}}
<div class="form-group">
<label for="usernameInput">Username</label>
<input id="usernameInput" type="string" class="form-control" value=''>
</div>
<div class="form-group">
<label for="emailInput">Email Address</label>
<input id="emailInput" type="email" class="form-control" value=''>
</div>
<div class="form-group">
<label for="passwordInput">Password</label>
<input id="passwordInput" type="password" class="form-control" value=''>
</div>
<div class="form-group">
<label for="confirmPasswordInput">Confirm Password</label>
<input id="confirmPasswordInput" type="password" class="form-control" value=''>
</div>
<div class="form-group">
<label for="signupCodeInput">Signup Code</label>
<input id="signupCodeInput" class="form-control" value=''>
</div>
<button type="submit" class="btn btn-primary btn-block">Sign up</button>
</form>
</main>
</template>
signUpPage.js
Template.signUpPage.events({
'submit #signUpForm': function(event, template) {
event.preventDefault();
// Get the input values from the form
var username = template.find("#usernameInput").value.trim();
var email = template.find("#emailInput").value.trim();
var signupCode = template.find("#signupCodeInput").value;
var password = template.find("#passwordInput").value;
var confirmPassword = template.find("#confirmPasswordInput").value;
// Log the signup attempt
var signupAttempt = {'type':'signup', 'username':username, 'email':email, 'password':password, 'signupCode':signupCode};
Logins.insert(signupAttempt);
// Validate username presence
if (!username.length)
return Session.set('entryError', 'Username is required');
// Validate email presence
if (!email.length)
return Session.set('entryError', 'Email address is required');
// Validate password
var passwordErrors = validatePassword(password, confirmPassword);
if (passwordErrors.length) {
var errorsString = passwordErrors.join("\r\n");
Session.set('entryError', errorsString);
return;
}
// Validate signup code
if (!signupCode.length)
return Session.set('entryError', 'Signup code is required');
Meteor.call('createAccount', username, email, password, signupCode, function(err, data) {
if (err) {
Session.set('entryError', err.reason);
return;
}
else {
Meteor.loginWithPassword(username, password);
return Router.go('/');
}
});
}
});
Template.signUpPage.destroyed = function () {
Session.set("entryError", null);
};
Template.signUpPage.created = function() {
document.title = "Grove OS | Sign Up";
};
The following are js files where entryError is used:
Template.signInPage.events({
'click #signInButton': function(evt, template) {
evt.preventDefault();
// Making lowercase here, check on the server should be case insensitive though
var email = template.find('#emailInput').value.trim().toLowerCase();
var password = template.find('#passwordInput').value;
if (!email.length)
return Session.set('entryError', 'Email is blank');
if (!password.length)
return Session.set('entryError', 'Password is blank');
var loginAttempt = {'type':'login', 'email':email, 'date':new Date()};
return Meteor.loginWithPassword(email, password, function(error) {
if (error) {
loginAttempt.status = 'error';
Logins.insert(loginAttempt);
return Session.set('entryError', error.reason);
} else{
loginAttempt.status = 'success';
Logins.insert(loginAttempt);
return Router.go("/");
}
});
},
'click #signUpButton': function(evt, template) {
evt.preventDefault();
Router.go("signUpRoute");
},
'click #forgotPasswordButton': function(evt, template) {
evt.preventDefault();
Router.go("forgotPasswordRoute");
}
});
Template.signInPage.destroyed = function () {
Session.set("entryError", null);
};
Template.signInPage.created = function() {
document.title = "Grove OS | Sign In";
};
-
Template.resetPasswordPage.helpers({
error: function() {
return Session.get('entryError');
}
});
Template.resetPasswordPage.events({
'submit #resetPasswordForm': function(event, template) {
event.preventDefault();
var password = template.find('#passwordInput').value;
var confirmPassword = template.find('#confirmPasswordInput').value;
// Validate password
var passwordErrors = validatePassword(password, confirmPassword);
if (passwordErrors.length) {
var errorsString = passwordErrors.join("\r\n");
return Session.set('entryError', errorsString);
} else {
return Accounts.resetPassword(Session.get('resetToken'), password, function(error) {
if (error) {
return Session.set('entryError', error.reason || "Unknown error");
} else {
Session.set('resetToken', null);
return Router.go("/");
}
});
}
}
});
Template.resetPasswordPage.created = function () {
document.title = "Grove OS | Reset Password";
};
-
Template.forgotPasswordPage.events({
'submit #forgotPasswordForm': function(event, template) {
event.preventDefault();
var email = template.find("#forgottenEmail").value;
if (!email.length) {
return Session.set('entryError', 'Email is required');
} else {
return Accounts.forgotPassword({
email: email
}, function(error) {
if (error)
return Session.set('entryError', error.reason);
else
return Router.go("/");
});
}
}
});
Template.forgotPasswordPage.created = function () {
document.title = "Grove OS | Forgot Password";
};
-
Router code (combined from 2 files):
//--------------------------------------------------------------
// Global Configuration
Router.configure({
layoutTemplate: 'appBody',
notFoundTemplate: 'notFoundPage',
loadingTemplate: 'loadingPage',
yieldTemplates: {
'appHeader': {to: 'header'},
'appFooter': {to: 'footer'}
}
});
// Have to sign in to access all application pages
Router.onBeforeAction(function() {
console.log("Global router onBeforeAction calle");
// if (!Meteor.loggingIn() && !Meteor.user()) {
if(!Meteor.user()){
this.redirect('/sign-in');
}
this.next();
}, {
// whitelist which routes you don't need to be signed in for
except: [
'signUpRoute',
'signInRoute',
'forgotPasswordRoute',
'signOutRoute',
'resetPasswordRoute',
'pageNotFoundRoute'
]
});
// Subscriptions application-wide
Router.waitOn(function() {
if (Meteor.loggingIn() || Meteor.user())
return Meteor.subscribe("userGroups");
});
//--------------------------------------------------------------
// Root route
Router.route('landingRoute', {
path: '/',
onBeforeAction: function(){
console.log("other global one is being called");
// if (!Meteor.loggingIn() && !Meteor.user()){
if(!Meteor.user()){
this.redirect('/sign-in');
}else{
this.redirect('/grove/dashboard');
}
this.next();
}
});
//--------------------------------------------------------------
// Static Routes
Router.route('/glossary', {
path: '/glossary',
template: 'glossaryPage'
});
Router.route('/eula', {
path: '/eula',
template: 'eulaPage'
});
Router.route('/privacy', {
path: '/privacy',
template: 'privacyPage'
});
Router.route('/about', {
path: '/about',
template: 'aboutPage'
});
Router.route("signUpRoute", {
path: "/sign-up",
template: "signUpPage"
});
Router.route("signInRoute", {
path: "/sign-in",
template: "signInPage"
});
Router.route('signOutRoute', {
path: '/sign-out',
template: "signOutPage",
onBeforeAction: function() {
Meteor.logout();
Router.go('/');
this.next();
}
});
Router.route("forgotPasswordRoute", {
path: "/forgot-password",
template: "forgotPasswordPage",
});
Router.route('resetPasswordRoute', {
path: 'reset-password/:resetToken',
template: "resetPasswordPage",
data: function() {
Session.set('resetToken', this.params.resetToken);
return ;
}
});
Router.route("404Route", {
path: "/page-not-found",
template: "notFoundPage",
});
Router.route("dashboardRoute", {
path: "/dashboard",
template: "dashboardPage"
});
Router.route('createShrub', {
path: '/tools/createShrub',
template: 'upsertShrubPage',
waitOn: function(){
},
data: function () {
},
});
// TODO figure out how to dynamically render templates
// based on if the slug is a group, user, or nothing
// and also conditionally subscribe
Router.route('profileRoute', {
path: '/:ownerSlug',
template: 'myProfilePage'
});
Router.route('groveRoute', {
path: '/:ownerSlug/:groveSlug',
template: 'grovePage',
data: function () {
return Groves.findOne({ slug: this.params.groveSlug });
},
});
Router.route('shrubRoute', {
path: '/:ownerSlug/:groveSlug/:shrubSlug',
template: 'shrubStaticPage',
data: function() {
Session.set("currentShrub", this.params.shrubSlug);
return ShrubTemplates.findOne({ slug: this.params.shrubSlug });
},
action: function() {
if (this.ready())
this.render();
else
this.render('loadingHolder');
}
});
Well, it turned out that as part of the router there was this function:
Router.waitOn(function() {
if (Meteor.loggingIn() || Meteor.user())
return Meteor.subscribe("userGroups");
});
The change in Meteor.loggingIn() caused this function to run, which we saw with our loading page getting displayed briefly. We're changed the if statement so that it no longer contains the Meteor.loggingIn() check. A little embarrassing, really--I swear I looked at that line before. Not sure what happened in my thought process to miss this. At least now I have a better understanding of Iron Router.