User interaction without login Angular? - javascript

On my website there are users and guests, and I want both to be able to "like" elements on my website. For the users it’s not a problem to check if they already "liked" a specific element to prevent them from giving another "like" to the same element, but I am not sure about how to check if the guest "liked" an element to prevent multiple likes from one specific guest. I am using Angular and I thought about saving such info with cookies, but I don’t know how yet, and if it will be trusted enough or not. Any ideas on how to implement them? Thanks.

Best way use localStorage , to be more complex use Hush (value and key ) in localStorage .
HTML
<button type="button" (click)="liked()">
<span *ngIf="!unlike">like</span>
<span *ngIf="unlike">unlike</span>
{{like}}
</button>
TS
like=99
unlike:Boolean=true
liked(){
if(localStorage.getItem('like') == null){
localStorage.setItem('like','true')
this.like=this.like+1;
this.unlike =!this.unlike
}else{
localStorage.removeItem('like')
this.like=this.like-1
this.unlike =!this.unlike
}
}
like=99;
ipActionLike =['1','2'] ;
unlike:Boolean=true;
liked(){
//get information browser user ip
if(localStorage.getItem('like') == null){
for (var i = 0; i <this.ipActionLike.length; i++) {
if (this.itemArray[i] == ipUser) {
//remove ipUser from array
localStorage.removeItem('like');
this.like=this.like-1;
this.unlike =!this.unlike; }
else{
//push ipUser to array
localStorage.setItem('like','true')
this.like=this.like+1;
this.unlike =!this.unlike }
}
}
}else{
//push ipUser to array
localStorage.removeItem('like')
this.like=this.like-1
this.unlike =!this.unlike
}
}
Hope this helps.

Related

In Dynamics CRM, how can I stop a user from entering more than 4 "Yes"s in a grid?

In my Dynamics CRM Opportunity form, I've added a Sales Quota Distribution Grid. If more than four Yes's have been entered in the entire grid, I want a warning message (or something similar) to be shown. For example, lets say record "A" t has 4 fields marked "Yes". Record "B" account has zero. If I change one the distributions next to record "B", I want the warning message to appear.
How can I do this? If it is not possible to create a warning message for this situation, what are my options?
Update: I am working on a JavaScript event to get this to run. Please see code below. It is not yet working, and I could use some help debugging.
function getTotalYesCount(executionContext) {
var formContext == executionContext.getFormContext();
var allRows == null;
var attributeColl == null;
var idqualifyyescount;
var sowbomyescount;
var scopeyescount;
var closeyescount;
try {
//get rows - use the getControl method and pass the grid name.
allRows == gridContext.getGrid().getRows();
//loop through rows and get the attribute collection
allRows.forEach(function (row, rowIndex) {
//get the attribute Collection
attributeColl == row.data.entity.attributes;
switch (att.getName()) {
case "new_idqualify":
if (att.getValue() == "Yes") {
idqualifyyescount == idqualifyyescount +1;
case "new_sowbom":
if (att.getValue() == "Yes") {
sowbomyescount == sowbomyescount +1;
}
case "new_scope":
if (att.getValue() == "Yes") {
scopeyescount == scopeyescount +1;
}
case "new_close":
if (att.getValue() == "Yes") {
closeyescount == closeyescount +1;
}
}
if ((idqualifyyescount + sowbomyescount + scopeyescount +closeyescount) > 4) {
Xrm.Utility.alertDialog("More than 4 Yes's have been entered in the Sales Quota Distribution.");
}
}
}
}
}
I will do the following
Create Plugin
Trigger, Entity: Sales Quota Distribution
Fields, Yes/No fields (4)
Plugin Message: Create,Update(status changes and fields change),delete
Then I will check when creating or updating record of sales quota if opp is filled and if for the same opp record there are already 4 yes/no been filled then throw exception
I chose plugin as it is server side, so that no matter where you create a record (import, UI create, Interface) your plugin will fire and check the condition

AJAX call on PHP function won't make it enter a value to my Database

I've been working on a piece of code for a few days now but I somehow can't get this to pass the value 1 to my database.
Basically what I am trying to achieve is that once the user clicks the button "collect coins" it passes the value 1 to my database. Every day at 12 pm the column "dailyfree" is reset to 0 by a MySQL event so the next day the user can click the button again since the value of "dailyfree" in the database is 0 again. Still I don't want the user to be able to click "collect coins" before the value in the database has been reset.
The problem is that once the user click the button, it gives him the free coins but the value 1 does not get passed to the database. The column "dailyfree" is still 0 after clicking the button. Does anybody know why that is?
Just for your information: I am very new to coding!
Here is what I am working with right now.
Javascript:
function free(){
var str = "username";
var term = "searched_word";
var index = str.indexOf(term);
if (index != -1) {
var daily = 1;
$.ajax({
url:"/free?daily="+daily,
success:function(data){
try{
data = JSON.parse(data);
console.log(data);
if(data.success){
bootbox.alert("Success! You've claimed 100 free credits!");
}else{
bootbox.alert(data.error);
}
}catch(err){
bootbox.alert("Javascript error: "+err);
}
},
error:function(err){
bootbox.alert("AJAX error: "+err);
}
});
}
else {
bootbox.alert("Your username does not contain the searched_word!");}
}
function disDelay(obj){
obj.setAttribute('disabled','disabled');
setTimeout(function(){obj.removeAttribute('disabled')},86400)
}
The Button itself
<div class="text-right">
<button class="btn btn-success btn-block" id="free" onclick="free(); disDelay(this)">Collect free coins</button>
</div>
PHP
$freecoins = 100;
case 'free':
if(!$user)
exit(json_encode(array('success'=>false, 'error'=>'You must login to access the redeem.')));
$daily = 1;
if(!preg_match('/^[a-zA-Z0-9]+$/', $daily)) {
exit(json_encode(array('success'=>false, 'error'=>'Code is not valid')));
} else {
$sql = $db->query('SELECT * FROM `users` WHERE `dailyfree` = '.$db->quote($dailyfree));
if($sql->rowCount() != 0) {
$row = $sql->fetch();
if($row['user'] == $user['userid'])
exit(json_encode(array('success'=>false, 'error'=>'You have already redeemed your daily reward!')));
$db->exec('INSERT INTO `users` SET `dailyfree` = '.$dailyfree.' , `balance` = `balance` + '.$freecoins.' WHERE `userid` = '.$db->quote($user['userid']));
exit(json_encode(array('success'=>true, 'credits'=>$freecoins)));
} else {
exit(json_encode(array('success'=>false, 'error'=>'Code not found')));
}
}
break;
I really hope you can help me find out why it won't enter the value into my database! Anyways, I wish you a very nice day :) Thanks for your help and time!
The query is wrong.
Should be a update query.
$db->exec('UPDATEusersSETdailyfree= '.$dailyfree.' ,balance=balance+ '.$freecoins.' WHEREuserid= '.$db->quote($user['userid']));
Or if you want to update when the user record present else insert the data then take a look at ON DUPLICATE KEY

How to add custom user data to meteor accounts

I'm trying to build out a system so that the default accounts sytem built into MeteorJS will have a friends list. Unfortunately, this just isn't working, and I can't figure out why. I'm currently attempting to simply add a friendList array to the user.profile, and then simply append the added user to the end of that list.
Here's the code:
Server:
Meteor.methods({
addFriend: function(friendUsername){
friendUserId = Meteor.users.findOne({username:friendUsername});
if(friendUserId){
Meteor.users.update({_id:Meteor.userId()}, {$set:{"profile.friendList":Meteor.user().profile['friendList'].push(friendUserId)}});
return 1;
}
else return 0;
}
});
Client:
Template.addFriendPage.events({
"keypress .addFriendByUsername": function(event, template){
if(event.which == 13){
event.preventDefault();
var user = Meteor.userId();
var friendUsername = template.find(".addFriendByUsername").value;
console.log(friendUsername);
console.log(user);
console.log(Meteor.call("addFriend",friendUsername));
if(Meteor.call("addFriend", friendUsername)){
alert("successfully added friend!");
template.find(".addFriendByUsername").value = "";
} else alert("not a valid username");
}
}
});
The html is just a template that I can put a username into. And I know I have to add in the part where I add the current user to the other user's friend list, but I want to get this working first.
Your main problem is you're setting a push. Instead, you need to use $push.
var userId = Meteor.user();
Meteor.users.update(userId, {$push:'profile.friendList':friendUserId});
Second, I'd consider it a moderately bad idea to store friends on the user profile. Consider creating a friends collection.

jQuery script fails executing for some of the users

I am using a custom form to submit data to Google Spreadsheets. When user attempts to submit the form, it is validated (with jQuery) and if the validation is passed, the main input field is being modified with jQuery and then the submission continues.
The user inputs a URL and during submission the script cuts off unnecessary parts of the link and adds IP (that is also gathered with jQ) of the user to it. After the modification is completed, the form continues submission and in result, only the modified data is being sent to Google Spreadsheet.
It works pretty well with 99% of submissions but there are several users whose browsers do not execute the script properly; i.e.: the URL they input is not being modified during the submission and thus, wrong data (unmodified) is sent to the Spreadsheet. I am not completely sure, but the problem may be caused by Firefox (but I am not 100% sure that all the faulty submission come from Firefox, if you want I could research and confirm whether it is only Firefox's issue). I have asked some of them (users, whose browsers seem not to execute script) about addons/if they had turned JS off but they say they did not do anything special with their browsers.
I am posting whole js file below so you could check whether I did some errors that could cause problems. Also, the script is running here (link), you can inspect the code to see what other jQuery stuff I use.
$(document).ready(function() {
//Tabbiing page is being initialised, doesn't really matter, I think
$.ionTabs("#fppp_taby");
//Script that checks whether user has been redirected back after submission, that's not the main problematic part yet
if (window.location.search != 0) {
var query = window.location.search.substring(1);
ideo = query.split("=")[1];
if (isNaN(ideo) || (ideo.length < 3) || (ideo.length > 10)) {
$("form").html("Wystąpił błąd podczas wysyłania Twojego zgłoszenia. Powiadom mnie o tym poprzez prywatną wiadomość podając również obecną godzinę za pomocą <a class='uline' href='http://www.erepublik.com/pl/main/messages-compose/2417512'>tego linka</a>.");
} else {
$("form").html("Dziękujemy za zgłoszenie!<br /><br />Możesz teraz przeczytać któryś z artykułów epolskiej prasy - lista wartch uwagi znajduje się po lewej stronie!");
var poZglosz = "Dziękujemy za zgłoszenie!<br />Spodziewaj się chlebków i broni od któregoś z tych graczy: Kijek93, twatwaratwa, Gregoric bądź Zawa99";
$("#poZglos").html(poZglosz);
$("#poZglos").removeClass();
}
} else {
var query = 0;
}
//Some simple stuff
$("#wlaczirc").click(function() {
$(this).hide();
$("#irc").html("<iframe src='http://webchat.quakenet.org/?channels=fppp&uio=OT10cnVlJjExPTM0OQ1f'></iframe>");
$("#irc").show("slow");
$("#info_irc").show("slow");
});
//Some data
infoPodkr = "Wklej tutaj prawidłowy link do twojego profilu!";
inputLink = $("#ffpolelinku");
//Resetting validation info in input
$(inputLink).focus(function() {
if ($(this).hasClass("podkresl") || $(this).val() == infoPodkr) {
$(this).val("");
$(this).removeClass("podkresl");
}
});
//Gathering ip
$.getJSON("http://jsonip.com/",
function(data) {
ip = data.ip;
});
//MAIN PART (executed when user pressses 'submit')
$("form").submit(function() {
//Form is being hidden (display:none class is being added)
$('aside').addClass("hidden");
//Check whether input is empty or contains error message (infoPodkr = error message vlaue), if yes, add class 'podkresl'
if (($(inputLink).val() == "") || ($(inputLink).val() == infoPodkr)) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
} else {
$(inputLink).removeClass("podkresl");
}
//Tesing whether user added proper link, if not, 'podkresl' is added
//if (!/\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&##\/%?=~_|!:,.;]*[\-A-Za-z0-9+&##\/%=~_|]/.test(inputLink.val())){
if (!/http\:\/\/www\.erepublik\.com\/[a-z]{2}\/citizen\/profile\/\d{5,}$/i.test(inputLink.val())) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
}
//Split link, and get the last part of it ('wycId'), check if it's numeral, if not - add 'podkresl' class
podzielony = $(inputLink).val().split('/');
wycId = podzielony.pop();
if (isNaN(wycId)) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
}
//Check whether the input class 'podkresl' class (= something was wrong in some of the steps above). If yes, remove the 'hidden' class from 'aside' which holds the form and show it to the user. If there were no errors, add the IP to the 'wycId' and additional "-n" to the end of the value and put it into input. Then, submit form.
if ($(inputLink).hasClass("podkresl")) {
$('aside').removeClass();
return false;
} else {
if (ip !== '') {
$(inputLink).val(wycId + "-" + ip + "-n");
} else {
$(inputLink).val(wycId + "-0-n");
}
}
return true;
});
});

How to repopulate form variables?

I've got a page that should warn if the user tries to leave the page having unsaved data. This dialog means "You have unsaved data. Do you want to conitnue?"
The problem is that the form values go blank when the user clicks a link to move on and is presented with the dialog. I want to form values to stay in place so that the user actually can choose not to continue and then still have left what was entered to the form.
The way the code is now is that it keeps a flag for whether the form has dirty data and that is a hidden variable:
<input type="hidden" name="saveStatus" value="<%=saveStatus%>" />
Touching the form sets this hidden variables with onclickand onkeypressed.
On the server I've got some logic that checks whether data is dirty:
public boolean returnToUnsavedData(ISessionHandler sessionHandler,
Action action) {
String saveStatus = sessionHandler.getRequestParameter("saveStatus");
if (saveStatus != null && !saveStatus.trim().equals("")) {
setHasUnsavedData(true);
} else {
setHasUnsavedData(false);
}
if (hasUnsavedData()) {
if (!"menuHasUnsavedDataOk".equalsIgnoreCase(action
.getActionCommand())
&& !action.getActionName().equals("Administrera")) {
ResourceBundle messages = ResourceBundle.getBundle("messages");
UserMessage um;
if (action.getActionCommand().equals("fastsearch")) {
um = new ExtendedUserMessage(
messages.getString("PV24"), UserMessage.TYPE_WARNING,
"Varning", action.getActionName(),
action.getActionCommand(), sessionHandler.getRequest().getParameter("fastsearch"));
} else {
um = new ExtendedUserMessage(
messages.getString("PV24"), UserMessage.TYPE_WARNING,
"Varning", action.getActionName(),
action.getActionCommand());
}
action.addUserMessage(um);
action.setReturnPage(action.getCurrPage());
setLatestActionTarget(action.getActionTarget());
return true;
} else {
setHasUnsavedData(false);
}
}
return false;
}
I suppose this is where I could check serverside for the variables and repopulate everything and then use a technique like above with the hidden variable to keep form values.
Do you think that this idea will work or can you present alternative solutions?
I don't think you need server-side involvement here, you can achieve this by using just javascript:
<input type="hidden" id="saveStatus" name="saveStatus" value="<%= saveStatus %>"/>
Register an observer before the page gets unloaded and check your saveStatus variable in there:
window.onbeforeunload = function() {
if (document.getElementById('saveStatus').value) {
return 'You have unsaved changes, are you sure you want to leave the page?');
}
};
However, by using this you will not have your own 'custom' confirmation screen, the browser's built in confirmation will be used (similar to stack-overflow's).

Categories

Resources