I am trying to add another user and I am experimenting with this code showed all around the internet.
So I tried this example below, it works fine, but how could I add another user, let's say for a guest?
is it possible? with like a conditional?
I am just trying to learn more about js and how I can solve this type of simple thing.
methods: {
login() {
if(this.input.username == "admin1" && this.input.password == "pass1") {
this.$store.commit("setAuthentication", true);
this.$router.replace({ name: "secure" });
} else {
console.log("The username and / or password is incorrect");
}
}
}
You Can use Below Code:
methods: {
login() {
if(this.input.username == "admin1" && this.input.password == "pass1") {
this.$store.commit("setAuthentication", true);
this.$router.replace({ name: "secure" });
} else if (this.input.username == "guest" && this.input.password == "guest1") {
// block of code to be executed if the condition1 is false and condition2 is true
}else {
console.log("The username and / or password is incorrect");
}
}
}
Related
e.preventDefault();
values = {
primery_key: 0,
name: $('#name').val(),
type: $('#type').val(),
cnic: $('#cnic').val(),
address: $('#address').val(),
mobile: $('#mobile').val(),
email: $('#email').val(),
ptcl_number: $('#ptcl_number').val(),
broker_pic: $('#broker_pic').val(),
};
if(values.name == '' || values.type == '' || values.cnic == '' || values.address == '' || values.mobile == '' || values.email == '' || values.ptcl_number == '' || values.broker_pic == '')
{
toastr.error('Please fill all the fields');
}
else
{
tempdb_conn.broker_table.add(values).unique(['primery_key']).then(function(id) {
toastr.success('Data saved successfully.');
$('#name').val('');
$('#type').val('');
$('#cnic').val('');
$('#address').val('');
$('#mobile').val('');
$('#email').val('');
$('#ptcl_number').val('');
$('#broker_pic').val('');
}).catch(function(e) {
toastr.error('Data already exist.');
});
}
I'm not that familiar with Dixie.js, but checking the documentation I'm guessing something like this...
In your collection every column you want to be unique needs to be a primary key.
See schema Schema Syntax at https://dexie.org/docs/Version/Version.stores()
Then use uniqueKeys()
https://dexie.org/docs/Collection/Collection.uniqueKeys()
Like this:
tempdb_conn.broker_table.add(values).uniqueKeys(function() {
toastr.success('Data saved successfully.');
$('#name').val('');
$('#type').val('');
$('#cnic').val('');
$('#address').val('');
$('#mobile').val('');
$('#email').val('');
$('#ptcl_number').val('');
$('#broker_pic').val('');
}).catch(function(e) {
toastr.error('Data already exist.');
});
I have a textarea where I need to put an object like that
[{
name: 'digitrust',
params: {
init: {
member: 'example_member_id',
site: 'example_site_id'
},
callback: function(digiTrustResult) {
if (digiTrustResult.success) {
var el = document.getElementById('dtidOutput');
console.log('Success', digiTrustResult.identity)
} else {
console.error('Digitrust init failed')
}
}
},
storage: {
type: 'html5',
name: 'pbjsdigitrust',
expires: 60
}
}]
I save this string in a mysql db and after I print it in a javascript object with php (laravel)
#if(!empty($useridobj))
try {
useridobj = {!! $useridobj !!};
if(typeof useridobj != 'object'){
useridobj = '';
}
} catch(err) {
useridobj = ''
}
#endif
If I put a correct obj in this textarea all works fine. But if I put something wrong like that
[{name:'digitrust',para]
console return an error.
So I'd like to validate the field first, in javascript (angular.js). I try something like that
if(!eval("var this_useridobj = "+ this.form.get("useridobj").value)){
this.form.get("useridobj").setErrors({ server: "UserId Object is not an object!" });
console.warn(this.form.get("useridobj"));
return false;
}
It doesn't work. Someone can help me please?
Thank u
Maybe you should validate in server side, eval or Function in the example above have some security issues, see this. Here you have a possible approach, but that Function executes anything:
document.getElementById("validate").addEventListener("click",()=>{
const json = document.getElementById("json").value;
const valid = (()=>{
try {
return (typeof (Function("return "+json))() === 'object')?true:false;
}
catch(error) {
return false;
}})();
console.log(valid)
});
//Try alert("something") in the textarea
<textarea id="json">{prop:[1,2,3}</textarea>
<button id="validate">
validate
</button>
I try to achieve an up or downvote button where a user is able to vote just 1 time up and 1 time down. If you already have upvoted something it should be possible to remove that with another click on the upvote button, but i dont know what is missing for this. My code looks like the following. I guess i have to implement something with a true of false statement but i tried some things and nothing worked. I would appreciate your help!
Template.postArgument.events({
'click':function() {
Session.set('selected_argument', this._id);
},
'click .yes':function() {
if(Meteor.user()) {
var postId = Arguments.findOne({_id:this._id})
console.log(postId);
if($.inArray(Meteor.userId(), postId.votedUp) !==-1) {
return "Voted";
} else {
var argumentId = Session.get('selected_argument');
Arguments.update(argumentId, {$inc: {'score': 1 }});
Arguments.update(argumentId, {$addToSet: {votedUp: Meteor.userId()}});
}
}
}});
Your general approach is correct however you don't need the Session variable at all or even the first click handler. And you don't need to return anything at all from the function.
Template.postArgument.events({
'click .yes': function(){
if ( Meteor.user() ) {
var post = Arguments.findOne({_id:this._id});
if ( $.inArray(Meteor.userId(), post.votedUp) === -1 ) {
Arguments.update(this._id, {
$inc: { score: 1 },
$addToSet: { votedUp: Meteor.userId() }
});
} else {
Arguments.update(this._id, {
$inc: { score: -1 },
$pull: { votedUp: Meteor.userId() }
});
}
}
}
});
You can start simple by checking for the existence of the user in the upvotes and downvotes and increment/decrement accordingly then add the user to the sets.
Meteor.methods({
'downvote post': function (postId) {
check(postId, String);
let post = Posts.findOne(postId);
Posts.update(postId, post.downvoters.indexOf(this.userId !== -1) ? {
$inc: { downvotes: -1 }, // remove this user's downvote.
$pull: { downvoters: this.userId } // remove this user from downvoters
} : {
$inc: { downvotes: 1 }, // add this user's downvote
$addToSet: { downvoters: this.userId } // add this user to downvoters.
});
}
});
Hello I am trying to implement a simple login feature using jQuery and PHP however the login keeps failing and I cannot figure out why.
This is the PHP function that deals with the login
function login()
{
$return = array(
'success' => false
);
if ($users[$_POST['login']] == $_POST['password']) {
$return = array(
'success' => true
);
$_SESSION['loggedIn'] = true;
}
print(json_encode($return));
}
The username is declared in a different PHP file and is declared like so.
$users['admin'] = '123654';
The following jQuery code should do the loging in.
$(self).on('click', '.loginSubmitButton', function() {
var username = $('#username').val().trim();
var password = $('#password').val().trim();
$.post(settings.server, {
login: username,
password: password
}, function(data) {
if (data.success == true) {
}
else {
alert('Wrong username or password!')
}
});
});
So far it doesnt implement anything in case of success because everytime I try to run this code and I enter the login credentials I get the Wrong username or password! alert.
You need to make the following changes to two sections:
PHP - add $users to function() like function($users) or add global as so:
function login()
{
global $users;
$return = array(
'success' => false
);
if ($users[$_POST['login']] == $_POST['password']) {
$return = array(
'success' => true
);
$_SESSION['loggedIn'] = true;
}
print(json_encode($return));
}
jQuery - As you are returning a JSON encoded string you need to parse it into jQuery:
$(self).on('click', '.loginSubmitButton', function() {
var username = $('#username').val().trim();
var password = $('#password').val().trim();
$.post(settings.server, {
login: username,
password: password
}, function(data) {
var data = JSON.parse(data);
if (data.success == true) {
}
else {
alert('Wrong username or password!')
}
});
});
I have a form with 5 input fields (4 text input, 1 checkbox) and I have written this code to handle missing information in the input fields. The code works fine but but it seems repetitive and inefficient. Is there a simpler way to write this code?
$("#main-form").on('submit', function(event) {
if (!$("#field1").val()) {
event.preventDefault();
$("#field1-error").html("Error!");
}
else
$("#field1-error").html("");
if (!$("#field2").val()) {
event.preventDefault();
$("#field2-error").html("Error");
}
else
$("#field2-error").html("");
if (!$("#field3").val()) {
event.preventDefault();
$("#field3-error").html("Error");
}
else
$("#field3").html("");
if (!$("#field4").val() && !$("#checkbox1").prop('checked')) {
event.preventDefault();
$("#field4-error").html("Error");
}
else
$("#field4-error").html("");
});
If the function does the same thing on multiple similar fields, it is best to just write one function. I think every Javascript engineer at some point or another has banged their head against a wall trying to come up with a slicker way run form validations.
For this situation I would write the function and call it whenever I needed it. Try this:
$("#main-form").on('submit', function(event) {
myValidations.contentsPresent('#field1', '#field1-error');//call the first field validaitions
myValidations.contentsPresent('#field2', '#field2-error');//second
//third
//etc
});
var myValidations =
{
contentsPresent: function(fieldId, errorId)
{
if (!$(fieldId).val()) {
event.preventDefault();
$(errorId).html("Error!");
}
else
$(errorId).html("");
}
},
contentsPresentCheckBox: function(fieledId, checkboxId, errorId)
{
if (!$(fieledId).val() && !$(checkboxId).prop('checked')) {
event.preventDefault();
$(errorId).html("Error");
}
else
$(errorId).html("");
}
}
}
//Try this.
$(document).ready(function(){
/** Form Validation */
$("#formId").validate({
rules: {
field1:{ required: true },
field2:{ required: true },
field3:{ required: true },
field4:{ required: true }
},
messages: {
field1:{ required: 'Field1 is required!' },
field2:{ required: 'Field2 is required!' },
field3:{ required: 'Field3 is required!' },
field4:{ required: 'Field4 is required!' }
}
// Submit function
});
// This is a simple jquery form validation but you need to include the jquery validation plugin.
http://jqueryvalidation.org/