My code has a simple issue that i cant figure out - javascript

I am setting up a link for my web page to take me to another site.
Ive tried everything i know how to do . my knowledge is limited though. basically when you visit https://beatsbycayde.com/roster/ it should take you to
"https://braytech.org/2/{destinyId}/{characterId}/legend"
for some reason it doesnt And I cannot figure out why any help would be greatly appreciated it it instead takes you to
https://braytech.org/2/{destinyId}/fstats/legend
I know that i have fstats in there iam trying to us it as an object and call it in the href
// get list of members and populate roster table
var roster = [];
$.when($.ajax({
url: "https://www.bungie.net/platform/GroupV2/699392/Members/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
}
}).success(function(json) {
if (json.ErrorStatus === 'Success') {
roster = json.Response.results;
console.log('Exalted member list:', roster);
} else {
alert('Uh oh, looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(json);
}
}).error(function(json) {
alert('Uh oh, looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(json);
}), $.ajax({
url: 'https://www.bungie.net/platform/destiny2/2/profile/4611686018429000034/?components=200',
headers: {
'X-API-Key': "47b810e692d64237911c2cbe0d433cfe"
}
}).success(function(res) {
console.log('PS4 stats:', res);
})).then(function() {
listMembers(roster);
});
function listMembers(rsp) {
var list = $('.memberList-list'),
on = 0,
sortMembers = function(method) {
// sort by date joined
if (method = joined) {
list.find('.member').sort(function(a, b) {
return ($(b).data('joined')) < ($(a).data('joined')) ? 1 : -1;
}).appendTo(list);
} else if (method = username) {
list.find('.member').sort(function(a, b) {
return ($(b).data('username')) < ($(a).data('username')) ? 1 : -1;
}).appendTo(list);
}
list.find('.member.online').prependTo(list);
};
for (var i = 0; i < rsp.length; i++) {
var profile = rsp[i].bungieNetUserInfo,
member = $('<a></a>');
// tally up online members
if (rsp[i].isOnline) {
on++
}
// check for valid profile
// some users don't have Bungie profiles somehow and it breaks function
if (typeof profile != 'undefined') {
// store response data in semantic variables
var name = rsp[i].destinyUserInfo.displayName,
joinDate = rsp[i].joinDate,
joined = joinDate.substring(0, joinDate.indexOf('T')),
online = rsp[i].isOnline,
icon = profile.iconPath,
memberId = profile.membershipId,
memberType = rsp[i].destinyUserInfo.membershipType,
destinyId = rsp[i].destinyUserInfo.membershipId,
rank = rsp[i].memberType;
// configure D OM node and add to page
$('#destiny-Id').text(destinyId);
$.ajax({
url: "https://www.bungie.net/Platform/Destiny/2/Account/" + destinyId + "/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
}
}).done(function(json) {});
$(function() {
$.ajax({
url: "https://www.bungie.net/Platform/Destiny/2/Account/4611686018429000034/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
},
success: function(data) {
// Gambit stats
var fstats = data.Response.data.characters[0].characterBase.characterId;
// Populate stats
// pvp
$('#player-f-stats').text(fstats);
},
error: function(data) {
alert('Uh oh, failed to load player stats! Looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log('Error loading player stats:', data);
}
});
});
member.attr({
'class': 'j-row vertical-center-row member',
'href': '/player/?bungieId=' + memberId + '&destinyId=' + destinyId + '&joined=' + joined + '&rank=' + rank,
'title': 'See player profile for ' + name,
'data-joined': joined.replace(/-/g, ''),
'data-username': name,
'data-online': 'false',
'data-searchable': name,
}).html('<div class="j-col j-col-1 member-icon"><img src="https://bungie.net/' + icon + '"></div>' + '<div class="j-col j-col-3 member-name"><h3>' + name + '</h3></div>' + '<div class="j-col j-col-3 member-joined" data-label="Joined">' + joined.replace(/-/g, '/') + '</div>' + '<div class="j-col j-col-3 member-status" data-label="Status"><span class="member-online" id="status-' + memberId + '">' + online + '</span></div>' + '<div class="j-col j-col-3 member-button"><a class="button outline gold full-width">' + 'View Stats' + '</a></div>' + '<div class="j-col j-col-3 member-button"> + In Depth Stats' + '</a></div>').appendTo(list);
// indicate online/offline status
if (String(online) === 'true') {
$('#status-' + memberId).text('Online').addClass('online').closest('.member').attr('data-online', true).addClass('online');
} else {
$('#status-' + memberId).text('Offline').removeClass('online');
}
sortMembers(joined); // sort members by join date
}
}
}

You have nested links. That breaks your HTML and prevents the href you want to be used.
Here you create the wrapper of each member. Which is a link.
member.attr({
'class': 'j-row vertical-center-row member',
'href': '/player/?bungieId=' + memberId + '&destinyId=' + destinyId + '&joined=' + joined + '&rank=' + rank,
...
And then you append another link inside of it here:
... In Depth Stats' ...
So I would suggest that you change the structure of your member element. Maybe place the top link in the position of the View Stats button and change that button to a <a> tag. But then as a consensus the whole member element won't be clickable, only the links.
Good luck!

Related

Pubnub One to One Chat Sending Message to all users

This is My Pubnub Chat Code
var pubnub = PUBNUB.init({
publish_key : 'my_key',
subscribe_key : 'sub-key'
});
pubnub.subscribe({
channel : "{{$channel}}",
message : function(m){
$(".conversation-list").append(
'<li class="clearfix '+ m.clearifix +' ">' +
'<div class="chat-avatar">' +
'<img src="' + m.image + '">'+
'<i> {{date('h:i')}} </i>' +
'</div>' +
'<div class="conversation-text">' +
'<div class="ctext-wrap">' +
'<i> '+ m.name + '</i>' +
'<p>' + m.message + '</p>' +
'</div>' +
'</div>' +
'</li>'
).animate({scrollTop: $(".conversation-list")[0].scrollHeight}, 0);
$('.reply-text').val('');
},
//connect : publish
});
$('.send-reply-to-user').on('click', function (e) {
e.preventDefault();
if ($('.reply-text').val()== '')
return false;
else
console.log(pubnub.publish);
// console.log(this);
var user_to_id = $(".send-reply-to-user").attr('user_to_id');
var message = $('.reply-text').val();
var name = $('#user_name').val();
var image = document.getElementById("user_image").getAttribute("src");
var clearifix = $('#user_clearifx').val();
pubnub.publish({
channel : "{{$channel}}",
message: { name : name, message : message, image : image, clearifix : clearifix }
});
if ($.trim(message).length != 0) {
$.ajax({
url: '{{route('send:user:chat:message')}}',
cache: false,
method: 'POST',
data: {user_to_id: user_to_id, message: message, _token: '{{csrf_token()}}'},
beforeSend: function () {
},
success: function (result) {
}
})
}
});
This code is Working perfectly only problem is that messages are going to all users, I want to send msg to one to one user.
Example: User one: John send a message to User two Deo,
Example 2: John sends a message to Marry
and so on. Using Pubnub JS API, Backend as Laravel 5.6
I recommend using PubNub's opinionated JavaScript framework called ChatEngine. It takes away a lot of the heavy lifting involved with making chat with PubNub. Here is some example code to get you started making 1:1 private chats. Make sure you use the setup button to prepare the backend on your account.
<script src="https://cdn.jsdelivr.net/npm/chat-engine#0.9.5/dist/chat-engine.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Init ChatEngine with PubNub
const publishKey = '__Your_PubNub_Publish_Key__';
const subscribeKey = '__Your_PubNub_Subscribe_Key__';
const ChatEngine = ChatEngineCore.create({
publishKey,
subscribeKey,
}, {
globalChannel: 'global',
});
const user = {
uuid: 'randomstringofchars',
name: 'John Smith'
}
const chats = {};
ChatEngine.connect(user.uuid, user);
ChatEngine.on('$.ready', function(data) {
// store my new user as `me`
let me = data.me;
// returns a ChatEngine chat object
function makePrivateChat(theirUserId) {
const chatKey = [theirUserId, me.uuid].sort().join('-');
// Don't make the same 1:1 chat if it already exists
if (chats[chatKey]) {
return;
}
// true for private chat
const chat = new ChatEngine.Chat(chatKey, true);
chats[chatKey] = chat;
}
// Auto add a 1:1 chat to UI when invited by someone
me.direct.on('$.invite', makePrivateChat);
// Define a button for making new 1:1 chats in your UI
newOneToOneChatButton.on('click', function (event, theirUserId) {
someChatObject.invite(theirUserId);
});
});
</script>
Finally Fixed My issue, the private Channels working good , Actually problem was with my back-end. It was returning data from all the users i have fixed now its working fine.

Check if file exists by checking two different naming conventions using jQuery/JS

I am trying to to build out profile pages for multiple users which include personalized photos/items that are stored are on a server. These items are labeled/named using the users' name. A user has a FirstName & LastName, with the option of using a PreferredName.
Initially, the items were named using PreferredName over Firstname if a Preferred Name existed. (ex: Fname: Robert; Lname: Smith; Pname: Bobby; FileName = SmithBobby.file)
Unfortunately, the user now has the ability to change their name on their profile from PreferredName back to FirstName, leading to a large portion of profiles to look for the incorrect file (item is actually named SmithBobby.file, while the profile is looking for SmithRobert.file.)
This being said, I would like to check for the item using both naming conventions (FirstLast.file & PreferredLast.file), if neither exists, it should default to use the default/generic photo. (default.file)
The below example is how I currently check to see if the user has a CV and profile picture on file. If no CV exists, it removes the element from the page. if the image doesn't exist, it defaults to default.jpg.
if (($.PageData.PreferredName == "") || ($.PageData.PreferredName == null)) {
$("#Name").text($.PageData.FirstName + " " + $.PageData.LastName);
document.title = ($.PageData.FirstName + " " + $.PageData.LastName + " | Profile");
$("#BioPageTitle").text($.PageData.FirstName + " " + $.PageData.LastName);
} else {
$("#Name").text($.PageData.PreferredName + " " + $.PageData.LastName);
document.title = ($.PageData.PreferredName + " " + $.PageData.LastName + " | Profile");
$("#BioPageTitle").text($.PageData.PreferredName + " " + $.PageData.LastName);
}
//FILENAME BUILD
var file_name = ($.PageData.LastName + $.PageData.FirstName);
var second_fname = ($.PageData.LastName + $.PageData.PreferredName);
file_name = file_name.replace(/[^0-9a-z]/gi, '');
second_fname = second_fname.replace(/[^0-9a-z]/gi, '');
var vita = $('#Vita');
var vita_url = "vita/" + file_name + ".pdf";
var second_vitaURL = "vita/" + second_fname + ".pdf";
var VitaLink = $("<a>").attr({
href: vita_url,
target: '_blank'
}).html("<strong>Curriculum Vitae</strong>");
$.get(vita_url)
.done(function() {
vita.html(VitaLink);
}).fail(function() {
vita.remove();
});
/*PHOTO BUILD/CHECK */
//PROFILE PICTURE
var img = $('#ProfilePicture');
var default_url = "photos/default.jpg";
var img_url = "photos/" + file_name + ".jpg";
img.error(function() {
$(this).attr('src', default_url);
});
img.attr('src', img_url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You should be able to extend your current function that checks the first link by checking for the second one if the first one fails. If the second one fails too, then you can remove the entry.
$.get(vita_url)
.done(function() {
vita.html(VitaLink);
}).fail(function() {
$.get(second_vitaURL)
.done(function() {
//modify the VitaLink with the correct url, if this doesn't work make a separate vitaLink type variable
VitaLink.attr('href', second_vitaURL);
vita.html(VitaLink);
}).fail(function() {
vita.remove();
});
});

Twitch Button (HTML/JScript w bootstrap)

Hello everyone I've tried everything I can think of to make this work. I know it does return stream = null or active through use in the browser, but It will not apply my buttons to my page. Not so good with javascript can anyone point me in the right direction.
<script type="text/javascript">
(function() {
var user_name, api_key;
user_name = "Undead_Atomsk";
api_key = "************************";
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name + '?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.write(Live!);
} else {
document.write(Offline!);
}
});
})();
</script
Took your advice and used browser tools "Completely forgot about those".
I added this line to my html.
I then made a .js file and used the following code everything works now the twitch API is just slow!
(function() {
var user_name, api_key, twitch_widget;
user_name = "Undead_Atomsk";
api_key = "********************";
twitch_widget = $("#twitch-widget");
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name +'?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.getElementById("twitch-btn").innerHTML = 'Live!';
} else {
document.getElementById("twitch-btn").innerHTML = 'Offline!';
}
});
})();

What is wrong with my foursquare api call?

The live example is here
http://kenziejoy.github.io/frontend-nanodegree-map/
I'm trying to pull data about locations that I have hard coded in an array - either by their foursquare id (didn't seem to be working) or their lat and lng. (client ID and secret are variables I just haven't shown them here)
I don't need any other functionality than just pulling data from their database to display on a map so I thought it would fall under the userless access but it is giving me an error that the request are bad because I don't have the proper authentication.
Thanks in advance
From the foursquare site
"Userless access
Some of our endpoints that don’t pertain to specific user information, such as venues search are enabled for userless access (meaning you don’t need to have a user auth your app for access). To make a userless request, specify your consumer key's Client ID and Secret instead of an auth token in the request URL.
https://api.foursquare.com/v2/venues/search?ll=40.7,-74&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=YYYYMMDD
To see what level of permissions each endpoint needs, check out the filters at the top of our endpoints page."
/**********FourSquare***************/
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&?client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
var result = data.response.venue;
var contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
var location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
var bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
var description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
var rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
var url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
var contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});
I took a look at the live example URL and you were getting a lot of bad request errors in the JavaScript console in Chrome.
Looking at these, you had a bad URL, you were using:
https://api.foursquare.com/v2/venues/search?limit=1&ll=45.5589522,-122.6517163&?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&v=20140806&m=foursquare
The problem seems to be that you have:
&?client_id
which makes the URL invalid.
Changing this to
&client_id
fixes this and I then see data coming back from Foursquare.

AngularJS - Open link in new tab when conditionally routing via controller

In my app, I have two types of profile for organisations. When a user click on a profile name, I first need to check whether I have a premium profile for that organisation, and if so, route the user in that direction. If there is no premium profile, the user is sent to the standard profile.
I'm doing this using ng-click, which send id and a resource (in this case, organisation) parameters to a controller, where the conditions are evaluated and then the user is routed in the correct direction. All of this works correctly when a user clicks as normal.
However, when a user tries to open the link in a new tab, by right clicking and selecting that option, the new tab opens with the url of the current page. So the ng-click and controller has not fired or evaluated the request before opening the new tab.
How can I change by code so that Angular processes the ng-click request before opening the new tab? Or more broadly, how can I allow my users to open one of these links in a new tab so that they are not just displayed the page they are currently on?
HTML
<div ng-controller="ProfileRouter">
<div ng-repeat="org in orgs | orderBy:'org.name'">
{{ org.name }}
</div>
</div>
Inside ProfileRouter controller
$scope.profileCheck = function (id, resource) {
$http({method: 'GET', url:'/IdCheck', params:{'id': id})
.success(function(data) {
var count = data.hits.found;
if (count) {
var hash = data.hits.hit[0].id;
}
if (resource == 'organisation') {
theResource = 'universities';
page = 'overview';
}
if (count == 1) {
window.location.href = "/" + theResource + "/profile/" + hash + "/" + page;
}
if (count == 0) {
window.location.href = "/" + resource + "/" + id;
}
})
.error(function(data) {
$scope.data = data || "Can't get resource";
});
}
I know this is an old question. But I found out a solution to this & posting it here might help someone else.
First of all I have created a custom directive for right click:
module.directive('tabRightClick',['$parse', function($parse) {
return function(scope, element, attrs) {
var fn = $parse(attrs.tabRightClick);
element.bind('contextmenu', function(event) {
scope.$apply(function() {
// event.preventDefault();
fn(scope, {$event:event});
});
});
};
}]);
Then applied this directive as an attribute in the HTML file and call the same method that is being called on ng-click:
<div ng-controller="ProfileRouter">
<div ng-repeat="org in orgs | orderBy:'org.name'">
{{ org.name }}
</div>
</div>
Here locationPath is a $scope bound variable, which we need to implement in the controller.
Its value should be updated in the profileCheck function based on the various conditions.
$scope.profileCheck = function (id, resource) {
$http({method: 'GET', url:'/IdCheck', params:{'id': id})
.success(function(data) {
var count = data.hits.found;
if (count) {
var hash = data.hits.hit[0].id;
}
if (resource == 'organisation') {
theResource = 'universities';
page = 'overview';
}
if (count == 1) {
window.location.href = "/" + theResource + "/profile/" + hash + "/" + page;
$scope.locationPath = "/" + theResource + "/profile/" + hash + "/" + page;
}
if (count == 0) {
window.location.href = "/" + resource + "/" + id;
$scope.locationPath = "/" + resource + "/" + id;
}
})
.error(function(data) {
$scope.data = data || "Can't get resource";
});
}
Hope it's helpful.

Categories

Resources