Showing alert after reloading page - javascript

I'm beginner just learn how to code, I try to make some notification after submitting form then reload page, will show alert-success bootstrap, this is the code
// Bootstrap alert
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message){
$('#alert_placeholder').html('<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><span>'+message+'</span></div>').show(500).delay(3000).hide(500);
}
(function checkIfMsgSent() {
if (typeof localStorage !== 'undefined') {
var isMsgSent = JSON.parse(localStorage.getItem("messageSent")); // JSON.parse because we want a boolean
if (isMsgSent) {
alert('Message has been sent.');
// bootstrap_alert.warning('Message has been sent.');
}
localStorage.removeItem('messageSent');
} else {
// localStorage not defined
alert('Your browser in incompatible for some features in this website');
}
});
$('#sentcontact').on('click', function(){
if (typeof localStorage !== 'undefined') {
localStorage.setItem('messageSent', 'true');
} else {
// localStorage not defined
alert('Your browser in incompatible for some features in this website');
}
window.location.reload();
});
Update Javascript Use by Solution 2
<div class="container">
<div id="alert_placeholder"></div>
</div>
<section class="contact_us">
<div class="container">
<form action="vanilla-form-contact.php" method="post">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="control-group">
<label for="name" class="label-control">Name:</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Your name..." required>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="control-group">
<label for="email" class="label-control">Email:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Your email..." required>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="control-group">
<label for="subject" class="label-control">Subject:</label>
<input type="text" class="form-control" name="subject" id="subject" placeholder="Your subject..." required>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="control-group">
<label for="message" class="label-control">Message:</label>
<textarea name="message" id="message" cols="30" rows="10" placeholder="Messages..." class="form-control" required></textarea>
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<img class="img-responsive" src="img/icon/contact.png" alt="Contact Icon">
<div>
<p class="title_contact">Contact:</p>
<p class="contact_phone"><i class="fa fa-phone-square"></i> +000</p>
<p class="contact_email"><i class="fa fa-envelope"></i> email#email.com</p>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<img class="img-responsive" src="img/icon/support.png" alt="Contact Icon">
<div>
<p class="title_contact">Support:</p>
<p class="contact_phone"><i class="fa fa-envelope"></i> email#email.com</p>
<p class="contact_email"></p>
</div>
</div>
</div>
</div>
<button type="submit" class="btn-custom" data-dismiss="alert" id="sentcontact">Send It</button>
</form>
This is my html
An error always show up when page reloaded in contact
It always show up in my page each time I reload page, not after clicking submit button
But, when I run that code, it just showing the bootstrap_alert first then reload the page. How could I make it reload page first then showing up bootstrap_alert?

There are a lot of ways to do it. An easy way to achieve this would be passing through a parameter in the URL and checking it on page load.
// Check the URL parameter on page load
$(function(){
if(getUrlParameter('success') == '1') {
bootstrap_alert.warning('Message has been sent.');
}
});
// Set up the click event
$('#sentcontact').on('click', function(){
if (true){
var nextUrl = window.location.href;
nextUrl += (nextUrl.indexOf('?') === -1 ? '?' : '&') + 'success=1'
window.location = nextUrl;
}
});
// Simple function to read parameters out of the URL
function getUrlParameter(name) {
var url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Solution 1
Modify href of the window when you programmatically reload, check for the hash fragment (onload) and decide to show the alert.
(function checkIfMsgSent() {
var url = window.location.href;
if ((/#message_sent/).test(url)) {
alert('Message has been sent.');
// bootstrap_alert.warning('Message has been sent.');
}
})();
$('#sentcontact').on('click', function(){
if (true){
window.location = window.location.href + "#message_sent";
window.location.reload();
}
});
Solution 2
Using localStorage, but this won't work if browser doesn't support localStorage (almost all modern browsers do have it).
(function checkIfMsgSent() {
if (typeof localStorage !== 'undefined') {
var isMsgSent = JSON.parse(localStorage.getItem("messageSent")); // JSON.parse because we want a boolean
if (isMsgSent) {
alert('Message has been sent.');
// bootstrap_alert.warning('Message has been sent.');
}
localStorage.removeItem('messageSent');
} else {
// localStorage not defined
alert('Your browser in incompatible for some features in this website');
}
})();
$('#sentcontact').on('click', function(){
if (typeof localStorage !== 'undefined') {
localStorage.setItem('messageSent', 'true');
} else {
// localStorage not defined
alert('Your browser in incompatible for some features in this website');
}
window.location.reload();
});

Related

Google invisible reCaptcha is only working in Incognito mode

I have a Google reCAPTCHA setup on my contact form in my website.
and i'm trying to test it in both localhost and server as well but recaptcha is only working in incognito mode .
without capturing reCAPTCHA mails are sending .
Here my problem is grecaptcha.execute(); is not executing, Please suggest solution for this.
$("#cont_msg").keypress(function (e) {
var key = e.which;
if (key == 13) {
// the enter key code
$("#contact_form_submit").click();
return false;
}
});
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).keypress(function () {
$(this).parent().removeClass("error");
});
function sendMail() {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
let data = {
username: co_name,
useremail: co_email,
userphone: co_phone,
usercompany: co_company,
usermessage: co_message,
};
$("#loading").show();
$("#contact_form_submit").hide();
$.ajax({
type: "POST",
url: "contact_ajaxmail.php",
data: data,
success: function (contact) {
//grecaptcha.execute();
$("#loading").hide();
$("#contact_form_submit").show();
var i = contact.split("#");
if (i[0] == "1") {
$("#cont_name").val("");
$("#cont_email").val("");
$("#cont_phone").val("");
$("#cont_company").val("");
$("#cont_msg").val("");
$("#contact_err").html(i[1]);
$(".app_form_wrapper .apps_input").addClass("success");
setTimeout(function () {
$(".app_form_wrapper .apps_input").removeClass("success");
$(".app_form_wrapper .apps_input").removeClass("error");
$("#cont_email").parent().removeClass("error");
}, 2500);
} else {
$("#cont_name").val(data.username);
$("#cont_email").val(data.useremail);
$("#cont_phone").val(data.userphone);
$("#cont_company").val(data.usercompany);
$("#cont_msg").val(data.usermessage);
$("#contact_err").html(i[1]);
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).each(function () {
if (!$(this).val()) {
$(this).parent().addClass("error");
} else {
if (i[0] == 3) {
$("#cont_email").parent().addClass("error");
} else {
$(this).parent().addClass("error");
}
$(this).parent().removeClass("error");
}
});
}
},
});
}
**My form**
Here iam trying to send mails for entered email
<!DOCTYPE html>
<html lang="en">
<!-- BEGIN HEAD -->
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<form class="app_form_wrapper" role="form" >
<div class="col-lg-6 text-left">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_name"placeholder="Name">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_email" placeholder="Email">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="tel" class="form-control" id="cont_phone" placeholder="Phone Number" minlength="10" maxlength="15">
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_company" placeholder="Company">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<textarea rows="10" class="form-control" id="cont_msg" placeholder="Message"></textarea>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="g-recaptcha"
data-sitekey="Site_key"
data-callback="sendMail"
data-size="invisible">
</div>
<p>
This site is protected by reCAPTCHA and the Google
Privacy Policy and
Terms of Service apply.
</p>
<a class="btn btn-default btn-lg contact_btn" id="contact_form_submit">Send</a>
<a class="btn btn-default btn-lg contact_btn" id="loading" style="display: none;">Sending...</a>
<p class="input_error"id="contact_err" style="color:#FF6666;position:absolute;font-size:14px;font-weight: 500;letter-spacing: 0.5px;bottom: 10px;left: 0;right: 0;">
</p>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#contact_form_submit").on("click", function () {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
if (
co_name != "" &&
co_email != "" &&
co_phone != "" &&
co_company != "" &&
co_message != ""
) {
grecaptcha.execute();
} else {
$("#loading").hide();
$("#contact_form_submit").show();
$("#contact_err").html("Please fill all the fields !!!!");
}
});
})
</script>
</body>
</html>
Captcha needs two things to make it work properly
Client side code in Javascript, this you have done by looks of it properly.
Server side code, without implementing server side code the captcha is useless as bots will just post straight to your PHP form without having to enter a captcha! This is your missing piece based on your comments.
See
https://developers.google.com/recaptcha/intro
Notice it says you need to do 2 steps, 1 client side, 2 verify the response:
https://developers.google.com/recaptcha/docs/verify
Google returns loads results but this seems to be an up to date article
https://phppot.com/php/php-contact-form-with-google-recaptcha/
Google implementing google captcha php

Check if username exist?

I have function that will be triggered on blur and send ajax request to check if username already exist in database. So far function works fine but I found one problem when user tries to update already saved username. Here is example of my code:
var usernames = ["jcook","mjones","kruffy"];
$(".check-account").focus(function() {
var submitBtn = $(this).closest("form").find(":submit");
submitBtn.prop("disabled", true); //Disable submit button on field focus.
$(this).attr('data-prev', $(this).val()); // Save current value in data attribute as data-prev.
if(!$(this).data("original")){
$(this).data("original",$(this).val());
}
}).blur(function() {
var fldObj = $(this),
submitBtn = $(this).closest("form").find(":submit");
if (fldObj.val() !== fldObj.data('prev') && fldObj.val() !== fldObj.data("original")) {
if ($.inArray(fldObj.val(), usernames) === -1) {
fldObj.data("original","");
fldObj[0].setCustomValidity("");
} else {
fldObj[0].setCustomValidity("User name already exist.");
}
submitBtn.prop("disabled", false);
} else {
fldObj[0].setCustomValidity("");
submitBtn.prop("disabled", false);
}
});
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frmSave" id="frmSave">
<input type="hidden" class="form-control" name="frm_recordid" id="frm_recordid">
<div class="form-group required">
<label class="control-label" for="username"><span class="label label-default">UserName:</span></label>
<input type="text" class="form-control check-account is-user" name="frm_username" id="frm_username" maxlength="50" required>
</div>
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-1 col-lg-1">
<button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-11 col-lg-11">
<div id="frm_message" class="alert"></div>
</div>
</div>
</form>
If you run my code example above you will see that my function will catch username if already exist. The problem that I have is when I try to edit data. Let's say I open form and user name will have value jcook. Then I try to enter different username for example mjones. If I try to submit form I will get message Username already exist!. Then if I try to put jcook again my code will trigger same message even I just try to put the same value that was already in the field for that record. I'm wondering how to avoid function trigger in this case if username was already saved for that record?

AngularJS 1.6.8: Form data not submitting and so hence unable to save it to localStorage

I have a contact form. On submission, it displays a success message and it should store that data to $localStorage.
But, Form data not is not submitting as I do not see submitted form data in response under network in dev tools and hence I am unable to save it to $localStorage.
below is the code for respective files.
link to plunker
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService) {
var vm = this;
vm.saveform = function(){
var name= vm.name;
var email= vm.email;
var query= vm.query;
console.log(name);
console.log(email);
console.log(query);
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted.";
$scope.user = userService;
};
$scope.navigate = function(home){
$state.go(home)
};
};
//localStorage code
function userService(saveform) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
There are no errors in console.

Unable to send email via ajax [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I need help to find what mistake I am doing , because I'm trying to develop a function that send email from a HTML form using php and ajax , the problem I'm facing is whenever I click on submit bouton the page is refreshing , usually as we can see in the javascript script , I'm supposed to receive a message that shows that it was successfully send
Best regards,
PHP File :
<?php
if (isset($_REQUEST['email'])) {
//Email information
$admin_email = "basselbizri#gmail.com";
$name = $_REQUEST['first_name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
//send email
if (mail($admin_email, $name, $message, "From:" . $email)) {
echo 1;
}
else {
echo 0;
}
}
?>
HTML Form :
<form class="inline" id="contactForm" method="post" >
<div class="row">
<div class="col-sm-6 height-contact-element">
<div class="form-group">
<input type="text" name="first_name" class="form-control custom-labels" id="name" placeholder="FULL NAME" required data-validation-required-message="Please write your name!"/>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-sm-6 height-contact-element">
<div class="form-group">
<input type="email" name="email" class="form-control custom-labels" id="email" placeholder="EMAIL" required data-validation-required-message="Please write your email!"/>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-sm-12 height-contact-element">
<div class="form-group">
<input type="text" name="message" class="form-control custom-labels" id="message" placeholder="WHAT'S ON YOUR MIND" required data-validation-required-message="Please write a message!"/>
</div>
</div>
<div class="col-sm-3 col-xs-6 height-contact-element">
<div class="form-group">
<input type="submit" class="btn btn-md btn-custom btn-noborder-radius" value="Send It"/>
</div>
</div>
<div class="col-sm-3 col-xs-6 height-contact-element">
<div class="form-group">
<button type="button" class="btn btn-md btn-noborder-radius btn-custom" name="reset">RESET
</button>
</div>
</div>
<div class="col-sm-3 col-xs-6 height-contact-element">
<div class="form-group">
<div id="response_holder"></div>
</div>
</div>
<div class="col-sm-12 contact-msg">
<div id="success"></div>
</div>
</div>
</form>
JS Script :
$('#contactForm').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
// get values from FORM
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var goodToGo = false;
var messgaeError = 'Request can not be send';
var pattern = new RegExp(/^(('[\w-\s]+')|([\w-]+(?:\.[\w-]+)*)|('[\w-\s]+')([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (name && name.length > 0 && $.trim(name) !='' && message && message.length > 0 && $.trim(message) !='' && email && email.length > 0 && $.trim(email) !='') {
if (pattern.test(email)) {
goodToGo = true;
} else {
messgaeError = 'Please check your email address';
goodToGo = false;
}
} else {
messgaeError = 'You must fill all the form fields to proceed!';
goodToGo = false;
}
if (goodToGo) {
$.ajax({
data: $('#contactForm').serialize(),
beforeSend: function() {
$('#success').html('<div class="col-md-12 text-center"><img src="images/spinner1.gif" alt="spinner" /></div>');
},
success:function(response){
if (response==1) {
$('#success').html('<div class="col-md-12 text-center">Your email was sent successfully</div>');
window.location.reload();
} else {
$('#success').html('<div class="col-md-12 text-center">E-mail was not sent. Please try again!</div>');
}
},
error:function(e){
$('#success').html('<div class="col-md-12 text-center">We could not fetch the data from the server. Please try again!</div>');
},
complete: function(done){
console.log('Finished');
},
type: 'POST',
url: 'js/send_email.php',
});
return true;
} else {
$('#success').html('<div class="col-md-12 text-center">'+messgaeError+'</div>');
return false;
}
return false;
});
});
In your success() method you're reload()'ing the page.
if (response==1) {
$('#success').html('<div class="col-md-12 text-center">Your email was sent successfully</div>');
window.location.reload(); // <----- remove this; it's causing the page to reload
}
So when your mail() function resolves true, in your PHP file (send_email.php), you're returning 1 to your AJAX response which is allowing the if (response == 1) to satisfy, and then you're using window.location.reload() to reload the page. Removing window.location.reload(); will keep the page from reloading.

meteor rerender login form after log in

I have a Meteor and login form like this:
<template name="index">
<h3>Index Page</h3>
{{#if currentUser}}
You are logged in!<br>
Dashboard
{{else}}
{{> loginForm}}
{{/if}}
</template>
<template name="loginForm">
<div class="container">
<div class="row col-md-offset-2 col-sm-offset-2">
<div class="container col-md-2 col-sm-2">
<h4>Login</h4>
</div>
<div class="container col-md-4 sol-sm-4">
<h4><small>or register</small></h4>
</div>
</div>
<!--div class="row"-->
<form class="form-horizontal" id="formLogin">
<div class="form-group">
<div class="col-md-2 col-sm-2">
<label for="inputEmail" class="control-label pull-right">Email</label>
</div>
<div class="col-md-4 col-sm-4">
<input type="email" class="form-control" id="inputEmail" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-md-2 col-sm-2">
<label for="inputPassword" class="control-label pull-right">Password</label>
</div>
<div class="col-md-4 col-sm-4">
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
</div>
<!--<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
</div>-->
<div class="form-group">
<div class="col-md-offset-2 col-sm-offset-2 col-md-10 col-sm-6">
<input type="submit" class="btn btn-default" value="Sign in">
</div>
</div>
</form>
<!--/div-->
</div>
<!-- END loginForm END -->
</template>
Here the JavaScript code for template:
Template.loginForm.events({
"submit #formLogin": function(e, t) {
e.preventDefault();
//console.log("Form login submitted");
var loginForm = $(e.currentTarget),
email = loginForm.find("#inputEmail").val(),
password = loginForm.find("#inputPassword").val();
//console.log("Email:" + email + "\n" + "Password:" + password);
//++++++ Validation
var trimInput = function(val) {
return val.replace(/^\s*|\s*$/g, "");
};
isEmailValid = trimInput(email).length > 5 ? true : false
//console.log(isEmailValid);
isPasswordValid = password.length > 0 ? true : false
//console.log(isPasswordValid);
//------
if (isEmailValid && isPasswordValid) {
Meteor.loginWithPassword(email, password, function(err) {
if (err) {
if (err.message === "User not found [403]") {
console.log("User does not exist.");
} else if (err.message === "Incorrect password [403]") {
console.log("Incorrect password");
} else if (err.message === "Match failed [400]") {
console.log("Match failed");
} else {
console.log(err.message)
}
} else {
return true;
}
});
} else {
console.log("Incorrect data");
};
}
});
After success login user shouldn't see the form. But if I refresh the page login form appear for 1-1,5 seconds and dissapear. How avoid this?
I had the same issue and this is how I solved it.
put:
if (Meteor.userId()) Router.go("main");
return false;
after your Meteor.loginWithPassword call
ie, for iron router and "main" as the template to render after login
When you do a page refresh the server will log in again as you are creating a new session in effect, it will automatically pick up the fact that you were previously logged in and log you in using those details. However for that period it will not have a userId and currentUser is null. It will however have a loggingIn state of true Meteor.loggingIn() which you are not checking for. To avoid confusion, check for the loggingin state and then show a loading screen or spinner to indicate something is happening.
You can create a global loggingIn handlebars helper:
if (Handlebars) {
Handlebars.registerHelper('loggingIn', function () {
return Meteor.loggingIn();
});
}
and then use that to display a loading/spinner template whilst the server is processing the login request after your page refresh:
{{#if currentUser}}
You are logged in!<br>
Dashboard
{{else}}
{{#if loggingIn}}
{{> loading}}
{{else}}
{{> loginForm}}
{{/if}}
{{/if}}
Which should solve the problem of the app presenting the login screen to the user on first page call/refresh and causing confusion, it will also let them know it is doing something whilst it is working away in the background to log them in.
If you still see the login form it should be really really minimal and flash up very quickly before reverting to either login or loading template.

Categories

Resources