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!';
}
});
})();
Related
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!
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.
i am developing an application and loading an hosted application using the inapp browser plugin cordova-plugin-inappbrowser
I have gotten most of the functionalities to work but i am unable to get the part of loading an error message when he url does not load, it dosent just work and shows me an error message of the url where i have hosted my application instead.
Which could be embarrassing.
please i need help on this
This is what am working with below thanks for ur potential responses
// my child browser code, the main source of my app content
function fire(){
var ref = cordova.InAppBrowser.open('http://####################', '_blank', 'location=no,zoom=no,hardwareback=yes,clearsessioncache=yes,clearcache=no');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', inAppBrowserbLoadStart);
ref.addEventListener('loadstop', inAppBrowserbLoadStop);
ref.addEventListener('loaderror', loadErrorCallBack);
ref.addEventListener('exit', inAppBrowserbClose);
}
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage =
"alert('Sorry we cannot open that page. Message from the server is : "
+ params.message + "');"
inAppBrowserRef.executeScript({ code: scriptErrorMesssage }, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function executeScriptCallBack(params) {
if (params[0] == null) {
$('#status-message').text(
"Sorry we couldn't open that page. Message from the server is : '"
+ params.message + "'");
}
}
Your code is generally fine, but you have no control over the title of the alert() function. You can use some other techniques to display the error message. For example, you can use a div:
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage = createMsg('Sorry we cannot open that page. Message from the server is: '
+ params.message);
inAppBrowserRef.executeScript({
code: scriptErrorMesssage
}, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function createMsg(msg) {
return 'var div = document.createElement("div");'
+ 'div.style.position = "absolute";'
+ 'div.style.top = "50%";'
+ 'div.style.left = "50%";'
+ 'div.style.width = "100px";'
+ 'div.style.height = "100px";'
+ 'div.style.color = "#f00";'
+ 'div.innerHTML = "' + msg + '";'
+ 'document.appendChild(div);'
}
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.
I have to develop an app using phonegap (HTML5, css, javascript, json, jquery,...).
This app should have to open an external website (using inAppBrowser) to login and then go back to the app providing a token.
Now I can open the external website but I don't know how to go back to the app.
Can someone help me?
Thanks
Omar
I just wrote some code roughly to retrieve data from external website. Hope this helps:
var yourApp = {
getData : function(q) {
var search_url = "http://xyz.com/xyz/customfeed?filterby=custom&urlfilter=1&" + q;
$("#loading").show();
$.ajax({
type: 'GET',
url: search_url,
dataType: 'xml',
success: function(xml) {
$('entry', xml).each(function() {
var hi = new xyzDataItem();
hi.title = $(this).find('title:eq(0)').text();
hi.link = $(this).find('link:eq(0)').attr('href');
hi.desc = $(this).find('summary:eq(0)').text();
hi.date = $(this).find('updated:eq(0)').text();
hi.id = $(this).find('id:eq(0)').text();
$("#loading").hide();
$("#search_results").append('<div class="abc">' +
'<h2>' + hi.title + '</h2>' +
'<P>' + hi.desc + '</p>' +
'<P>xyzData</p>' +
'</div>');
});
}
});
}
}
If you are using InAppBrowser then do the following:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function(event) {
if (event.url,indexOf("http://apache.org") > -1){
//do something
}
});
}
Ideally the token should be part of the URL so that it is easier to retrieve. Else use $.getJSON method and do not use InAppBrowser. But if using InAppBrowser then the token should be a query string parameter.
E.g. http://yoursite.com/loginsuccess?token=adsfsadfdsfasdf