Facebook Javascript SDK show value of array - facebook-graph-api

I'm trying to show the tags of a checkin in facebook javascript sdk, but shows only [object Object] because it is an array, I tried several ways to show this array, but could not.
The following code:
<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>New JavaScript SDK</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
window.fbAsyncInit = function() {
FB.init({
appId: '274371602680881',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
var userInfo = document.getElementById('user-info');
FB.api('/me', function(response) {
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture">' + response.name;
button.innerHTML = 'Uninstall';
FB.api('/me/checkins', function(response) {
console.log('Got your check-ins: ', response);
if (!response.error) {
//displayCheckIns(response.data, document.getElementById('checkins'));
var markup = '<div class="data-header">Your last five check-ins:</div>';
for (var i=0; i < response.data.length && i < 5; i++) {
var checkin = response.data[i];
//alert(checkin.tags);
//alert(checkin.tags.length);
//alert(checkin.tags.name);
//alert(checkin.tags[0]);
//alert(checkin.tags[0].name);
markup += '<div class="place">'
+ '<div class="picture">Foto: <img src="http://graph.facebook.com/' + checkin.place.id + '/picture"></div>'
+ '<div class="info">'
+ '<div class="from">From: ' + checkin.from.name + '</div>'
+ '<div class="tags">Tags: ' + checkin.tags + '</div>'
+ '<div class="place">Place: ' + checkin.place.name + '</div>'
+ '<div class="place-location">Place Location: ' + checkin.place.location.latitude + ", " + checkin.place.location.longitude + '</div>'
+ '<div class="application">Application: ' + checkin.application.name + '</div>'
+ '<div class="created_time">Created time: ' + checkin.created_time + '</div>'
+ '<div class="likes">Likes: ' + checkin.likes + '</div>'
+ '<div class="check-in-msg">Mensagem: ' + (checkin.message || '') + '</div>'
+ '<div class="comments">Comments: ' + checkin.comments + '</div>'
+ '</div>'
+ '</div>';
}
document.getElementById('user-checkins').innerHTML = markup;
}
});
});
button.onclick = function() {
FB.api({
method: 'auth.revokeAuthorization'
}, function(response) {
window.location.reload();
});
/*
FB.logout(function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML="";
});*/
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture" style="margin-right:5px"/>' + response.name;
});
} else {
//user cancelled login or did not grant authorization
}
}, {
scope:'user_status'
});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
});
</script>
</head>
<body>
<div id="fb-root"></div>
<h2>Updated JS SDK example</h2><br />
<div id="user-info"></div>
<div id="user-checkins"></div>
<p><button id="fb-auth">Login</button></p>
</body>
</html>
I tried a few ways, such as:
checkin.tags // shows [object Object]
checkin.tags.length // shows undefined
checkin.tags.name // shows undefined
checkin.tags[0] // shows undefined
checkin.tags[0].name // Can not read property 'name' of undefined
This happens with tags, likes and comments. The others that are NOT array works fine, like "checkin.place.name", and even "checkin.place.location.latitude" brings the correct value.
I did an "console.log(JSON.stringify(checkin.tags));" and it returns:
{"data":[{"id":"100001702765878","name":"Mauricio Forte Neto"},{"id":"100001174670611","name":"Mario Celso"}],"paging":{"next":"https://graph.facebook.com/402127889842448/tags?access_token=AAAD5ih3qDDEBAIo3nB8P3ZCAwXrivw5lunDRAUvkRZCCFZBUy5au3ImicViq80HHVZC29hLDit6QwlZCXZB5WEBkDF3Pp2DrnUGWLrAwhpWddLoliyFDqd&limit=25&offset=25&__after_id=100001174670611"}}
Please, help.
Thanks in advance.

Since it's an object and has data in it, I have to request the data type in it.
What I been missing is to add an ".data" like:
checkin.tags.data[0].name
Now it works!!!

Related

Show and Hide Bootstrap Modal for displaying Loading Image

I have a modal with a GIF image that i used for Loadin instead of using spinners. However there are times that the modal_loading is not hiding after calling the hide_loading function.
<script>
function show_loading(title="", message=""){
$('#loading_title').html('');
$('#loading_message').html('');
if(title != ""){
$('#loading_title').html("<h5 style='padding:7px;font-weight:bold'>"+ title + "</h5>");
}
if(message != ""){
$('#loading_message').html("<p style='padding:7px'>" + message + "</p>");
}
$('#modal_loading').modal('show');
}
function hide_loading(){
$('#modal_loading').on('shown.bs.modal', function (e) {
$("#modal_loading").modal('hide');
})
}
</script>
Here is my code.
function fetch_data(page, sort_type, sort_by) {
show_loading('Populating Table');
var filter = $('#form_filter').serialize();
$.ajax({
url: "/lrmis-learning_resources/get_ajax_data?sortby=" + sort_by + "&page=" + page + "&sorttype=" + sort_type + "&" + filter,
success: function(data) {
$('#my_table').html(data);
clear_icon();
if (sort_type == "desc") {
$('#' + sort_by + '_icon').html('<span class="fa fa-caret-down"></span>');
} else {
$('#' + sort_by + '_icon').html('<span class="fa fa-caret-up"></span>');
}
hide_loading();
}
});
}

SharePoint weather web part

Can any one help me to find out free weather forecast on my sharepoint 2013 site?
I found some limited calls APIs, but not completely free.
I did simple test by Yahoo Weather API.
Create an app in Apps, so you could use id&key&secret to request.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha1.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/enc-base64.js">
</script>
<script type="text/javascript">
var url = 'https://weather-ydn-yql.media.yahoo.com/forecastrss';
var method = 'GET';
var app_id = '80ggw87i';
var consumer_key = 'yourkey';
var consumer_secret = 'yoursecret';
var concat = '&';
var query = { 'location': 'sunnyvale,ca', 'format': 'json' };
var oauth = {
'oauth_consumer_key': consumer_key,
'oauth_nonce': Math.random().toString(36).substring(2),
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': parseInt(new Date().getTime() / 1000).toString(),
'oauth_version': '1.0'
};
var merged = {};
$.extend(merged, query, oauth);
// Note the sorting here is required
var merged_arr = Object.keys(merged).sort().map(function (k) {
return [k + '=' + encodeURIComponent(merged[k])];
});
var signature_base_str = method
+ concat + encodeURIComponent(url)
+ concat + encodeURIComponent(merged_arr.join(concat));
var composite_key = encodeURIComponent(consumer_secret) + concat;
var hash = CryptoJS.HmacSHA1(signature_base_str, composite_key);
var signature = hash.toString(CryptoJS.enc.Base64);
oauth['oauth_signature'] = signature;
var auth_header = 'OAuth ' + Object.keys(oauth).map(function (k) {
return [k + '="' + oauth[k] + '"'];
}).join(',');
$.ajax({
url: url + '?' + $.param(query),
headers: {
'Authorization': auth_header,
'X-Yahoo-App-Id': app_id
},
method: 'GET',
success: function (data) {
console.log(data);
debugger;
}
});
</script>
You need bind the data with proper CSS.

Optimize JSOM Query

I have the following SharePoint 2016 JSOM query that retrieve the list item based on the current user email...this query currently works, however, I have been doing some study around using jquery defferred and Promised objects. In order to rationalize how this methods works I want to optimize the existing code below
<script type="text/javascript" src="//code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
getCurrent();
//getMyTasks();
$('#checkall').click(function (e) {
$("#GetItems").find('td input:input[name=chk]').prop('checked', this.checked);
if($(this).is(':checked')) {
$('#Reject').removeAttr('disabled');
$('#Approve').removeAttr('disabled');
} else {
$('#Reject').attr('disabled', true);
$('#Approve').attr('disabled', true);
}
});
$('#GetItems').on('change', 'input[name=chk]', function(){
if($(this).is(':checked')) {
$('#Reject').removeAttr('disabled');
$('#Approve').removeAttr('disabled');
} else {
$('#Reject').attr('disabled', true);
$('#Approve').attr('disabled', true);
}
});
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', approve);
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', reject);
// approve();
//reject();
});
function getCurrent()
{
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=Email",
headers: { Accept: "application/json;odata=verbose" },
success: function (data) {
currentEmail=data.d.Email;
getMyTasks();
} ,
error: function (data) {
alert("failed to get email");
}
});
}
function getMyTasks(){
//var listTitle="hardware%20requisition";
var row = "";
var buttonrow="";
var url =_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EUS Asset Request')/Items?$select=ID,AssetMgrEmail,EUSPersonMailID,SRNo,AssetAvailability,Asset_x0020_Manager_x0020_Approv,Asset_x0020_Manager_x0020_Commen,Attachments,Department,Department_x0020_Head,Department_x0020_head_x0020_Appr,Department_x0020_head_x0020_appr1,Department_x0020_head_x0020_Appr0,HOD_x0020_Approval_x0020_Comment,IT_x0020_Head,IT_x0020_Head_x0020_Approval_x001,IT_x0020_head_x0020_Approval_x00,Items_x0020_Requested_x0020_For,IT_x0020_head_x0020_approval_x000,IT_x0020_head_x0020_Approved_x00,Job_x0020_Title,L1_x0020_Approval_x0020_Comments,L1_x0020_Approval_x0020_Date,L1_x0020_Approval_x0020_Status,L1_x0020_Approved_x0020_Date,L1_x0020_Supervisor_x0020_Email,Motivation,OPCO,Replacement_x0020_Type,Request_x0020_Summary,Request_x0020_Type,Requester_x0020_Name,EUSPersonMailID,Requester_x0020_Phone_x0020_Numb,ViewID,Author/Name,Author/EMail,Author/Title&$expand=Author/Id&$filter=EUSPersonMailID eq '"+currentEmail+"' and L1_x0020_Approval_x0020_Status eq 'Approved' and Department_x0020_head_x0020_appr1 eq 'Approved' and IT_x0020_head_x0020_approval_x000 eq 'Approved' and Asset_x0020_Manager_x0020_Approv eq 'Approved' and EUSTeamConfirmation eq 'Pending'"
$.ajax({
url: url,
type: "GET",
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
},
success: function(data){
var result = data.d.results;
if(result.length>0)
{
$("#divbuttons").show();
$.each(result, function(key, item)
{
var createdDate= moment(item.Created_x0020_Date).format("DD/MM/YYYY");
row = row + '<tr style="background-color: #cccccc;"><td style="width: 261.6px;"><strong>Select</strong> <input name="chk" type="checkbox" value='+ item.Id+' /></td><td style="width: 151.2px;"> </td><td style="width: 324.8px;"><strong>Request ID: </strong>'+item.ID+'</td><td style="width: 324.8px;"><strong>Requester Name: </strong>'+item.Author.Title+'</td><td style="width: 376.8px;"><strong>Phone Number:</strong><br />'+item.Requester_x0020_Phone_x0020_Numb+'</td><td style="width: 396px;"><strong>Department:</strong><br />'+item.Department+'</td><td style="width: 213px;"><strong>Request Type</strong><br />:'+item.Request_x0020_Type+'</td><td style="width: 4.8px;">Availability Status<br/>:'+item.AssetAvailability+'</td><td style="width: 213px;"><strong>Serial Number</strong><br />'+item.SRNo+'</td><td style="width: 213px;"><strong>EUS Person MailID</strong><br />'+item.EUSPersonMailID+'</td><td style="width: 213px;"><strong>Receiver MailID</strong><br />'+item.Author.EMail+'</td></tr>';
})
$("#GetItems>tbody").html(row);
$("#GetItems").show();
}
else{
$("#NoTask").show();
}
},
error: function(data){
alert("Failed to get list items.");
}
});
}
function approve(){
$("#Approve").click(function(event){
event.preventDefault();
var searchIDs = $("#GetItems input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var itemArray = [];
var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);
var oList = clientContext.get_web().get_lists().getByTitle("EUS Asset Request");
for(var i = 0; i< searchIDs.length; i++){
// alert($("#GetItems textarea#"+searchIDs[i]+"").val());
var oListItem = oList.getItemById(searchIDs[i]);
oListItem.set_item('EUSTeamConfirmation', 'Confirmed');
oListItem.set_item('ViewID', 'FinalVw');
oListItem.update();
itemArray[i] = oListItem;
clientContext.load(itemArray[i]);
}
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
function onQuerySucceeded() {
alert('Items Updated');
location.reload(true);
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
location.reload(true);
}
});
}
function reject(){
$("#Reject").click(function(event){
event.preventDefault();
var searchIDs = $("#GetItems input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var itemArray = [];
var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);
var oList = clientContext.get_web().get_lists().getByTitle("EUS Asset Request");
for(var i = 0; i< searchIDs.length; i++){
var oListItem = oList.getItemById(searchIDs[i]);
oListItem.set_item('EUSTeamConfirmation', 'Rejected');
oListItem.set_item('ViewID', 'RejectVw');
oListItem.update();
itemArray[i] = oListItem;
clientContext.load(itemArray[i]);
}
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
function onQuerySucceeded() {
alert('Task Rejected');
location.reload(true);
//getCurrent();
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
location.reload(true);
// getCurrent();
}
});
}
</script>
<div id="NoTask" style="display:none">You don't have pending tasks for approval</div>
<div style="display:none" id="divbuttons"><input type="checkbox" id="checkall"></input><button type="button" id="Reject" disabled>Reject</button><button type="button" id="Approve" disabled>Approve</button></div>
<table id="GetItems" cellspacing="12"><tbody></tbody> </table>
Kindly assist

Need to add direct checkout instead of adding to the cart in opencart 2.3.0.2

Orignal code from opencart:-
var cart = {
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
complete: function() {
$('#cart > button').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>');
// Need to set timeout otherwise it wont update the total
setTimeout(function () {
$('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
}, 100);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
},
I tried to edit these way but it had no effect on the front end everything was same
check below i tried replacing the code here:-
var cart = {
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
complete: function() {
$('#cart > button').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
if (json['redirect']) {
location = json['redirect'];
}
//here i replaced the code
if (json['success']) {
window.location='index.php?route=checkout/checkout';
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
},
can anyone kindly help me out with these opencart 2.3.0.2 problem..??
This should work, I'm on 2.3.0.2 and have multiple stores using this in the Success statement to redirect to the cart page after clicking add to cart.
window.location.href = "index.php?route=checkout/cart";
Obviously you'd want to change it to:
window.location.href = "index.php?route=checkout/checkout";
Good luck!
replace the redirect function where you already changed with the code below
window.location='index.php?route=checkout/checkout';
with this code, this will redirect to your checkout.
location.href='index.php?route=checkout/checkout';

Can't get data from model to appear in template Ember.js

My code is here: http://jsfiddle.net/FNn4R/4/ I can't get the outgoings model (a model with messages outbound) to display in the template.
HTML
<script type="text/x-handlebars" data-template-name="messages">
Hello <b>{{App.username}}</b><br />
{{#each outgoings in model}}
<h4>{{outgoings.vehicle_reg}}</h4>
<p>{{outgoings.message_subject}}</p>
{{/each}}
</script>
JS
App.MessagesRoute = Ember.Route.extend({
model: function() {
return App.Outgoings.all();
},
renderTemplate: function() {
this.render('header-messages', {
into: 'application',
outlet: 'header'
});
this.render('messages', {
into: 'application',
outlet: 'content'
});
}
});
App.Outgoings = Ember.Object.extend();
App.Outgoings.reopenClass({
all: function() {
var outgoings = [];
var apiPage = "messages";
var parameters_string = "action=outgoing";
var url = "http://do-web-design.com/clients/carbuddy/index.php/api/";
var url = url + apiPage + "?" + parameters_string + "&username=" + "will" + "&password=" + "1234";
// console.log(url);
var response = $.ajax({
type: "GET",
url: url,
dataType: "text json",
success: function(data){
return data;
// return JSON.parse(data)
alert('Its working'); //It will alert when you ajax call returns successfully.
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' | ' + errorThrown);
}
}).done(function(response) {
response.forEach( function (outgoing) {
outgoings.push( App.Outgoings.create(outgoing) );
});
});
return outgoings;
}
});
My Ajax call is getting data but its just not copying it into the model and or sending it to the template.