I'm working on a website in which displays the reviews/ratings of a facebook page through the GRAPH API using JS and JSON calls to have the ratings. But there would be no way to read these assessments without an access token, since they are public information? Or one that lives more than 60 days.
<script id="erasable" type="text/javascript">
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
`enter code here`});
};
getJSON('https://graph.facebook.com/FACEBOOK-PAGE-ID/ratings?access_token=PAGE-ACCESS-TOKEN').then(function(data) {
//some html pos-processing
}, function(status) { //error detection....
//alert('Something went wrong.');
});
</script>
Related
I'm using this service worker for caching and offline mode.
when I am already on any existing page of my website and I request a non-existent page, the Offline page is served instead of the 404 page.
If, on the other hand, I close and reopen the browser and immediately request a non-existent page of my website, the 404 page is served correctly.
I suspect it has to do with these last few lines of the code
if(!matching || matching.status == 404) { return cache.match("/service/offline/"); but i don't know how to fix this problem. Can you help me please?
Here's the full service worker:
self.addEventListener("install", function(event) {
event.waitUntil(preLoad());
});
var preLoad = function(){
console.log("Installing web app");
return caches.open("offline").then(function(cache) {
console.log("caching index and important routes");
return cache.addAll([
'/assets/css/about.min.css',
'favicon.ico',
'/assets/js/script.js',
'manifest.webmanifest.webmanifest',
'/',
'/about/',
'/contact/',
'/service/offline/'
]);
});
};
self.addEventListener("fetch", function(event) {
event.respondWith(checkResponse(event.request).catch(function() {
return returnFromCache(event.request);
}));
event.waitUntil(addToCache(event.request));
});
var checkResponse = function(request){
return new Promise(function(fulfill, reject) {
fetch(request).then(function(response){
if(response.status !== 404) {
fulfill(response);
} else {
reject();
}
}, reject);
});
};
var addToCache = function(request){
return caches.open("offline").then(function (cache) {
return fetch(request).then(function (response) {
console.log(response.url + " was cached");
return cache.put(request, response);
});
});
};
var returnFromCache = function(request){
return caches.open("offline").then(function (cache) {
return cache.match(request).then(function (matching) {
if(!matching || matching.status == 404) {
return cache.match("/service/offline/");
} else {
return matching;
}
});
});
};
I am using 8th Wall SDK and trying to call an API. When I am attempting to do that from AFrame.registercomponent onclick method, the request is not getting sent.
I am new to AR. When I tried adding an alert messages for xhttp, it's empty.
What am I missing?
Is there an alternative to this?
By the way, I tried doing this with with an AR marker using Awe.js and it worked fine.
AFRAME.registerComponent('play-on-window-click', {
...
...
onClick: function(evt) {
var video = this.el.components.material.material.map.image;
// I'm sending a request from here - BEGIN
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.status == 200) {
this.responseText;
}
xhttp.open("GET", "https://myapi/rest/abc", true);
xhttp.send();
}
// END
video.play();
}
}
I expect the call is made successful to the API.
The xhttp.open and xhttp.send calls are inside the onreadystatechange handler so it will not get sent. Something like this should work:
AFRAME.registerComponent('play-on-window-click', {
...
...
onClick: function(evt) {
var video = this.el.components.material.material.map.image;
// I'm sending a request from here - BEGIN
var xhttp = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.status == 200) {
alert(this.responseText);
}
}
xhttp.open("GET", "https://myapi/rest/abc", true);
xhttp.send();
// END
video.play();
}
}
Upload Base64 Image Facebook Graph API
i want to use this script that link is attached how i can use this in my wordpress post?
i want to use this for fbcover photo site.
Take a look at this code I hacked together from various examples - you can use this to post a pure base64 string to the Facebook API - no server side processing.
Here's a demo: http://rocky-plains-2911.herokuapp.com/
This javascript handles the converting of a HTML5 Canvas element to base64 and using the Facebook API to post the image string
<script type = "text/javascript">
// Post a BASE64 Encoded PNG Image to facebook
function PostImageToFacebook(authToken) {
var canvas = document.getElementById("c");
var imageData = canvas.toDataURL("image/png");
try {
blob = dataURItoBlob(imageData);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token", authToken);
fd.append("source", blob);
fd.append("message", "Photo Text");
try {
$.ajax({
url: "https://graph.facebook.com/me/photos?access_token=" + authToken,
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data);
$("#poster").html("Posted Canvas Successfully");
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
console.log("Posted to facebook");
}
});
} catch (e) {
console.log(e);
}
}
// Convert a data URI to blob
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {
type: 'image/png'
});
}
</script>
This handles the Facebook Authentication and shows basic HTML setup
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
cache: true
});
$.getScript('//connect.facebook.net/en_UK/all.js', function () {
// Load the APP / SDK
FB.init({
appId: '288585397909199', // App ID from the App Dashboard
cookie: true, // set sessions cookies to allow your server to access the session?
xfbml: true, // parse XFBML tags on this page?
frictionlessRequests: true,
oauth: true
});
FB.login(function (response) {
if (response.authResponse) {
window.authToken = response.authResponse.accessToken;
} else {
}
}, {
scope: 'publish_actions,publish_stream'
});
});
// Populate the canvas
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.font = "20px Georgia";
ctx.fillText("This will be posted to Facebook as an image", 10, 50);
});
</script>
<div id="fb-root"></div>
<canvas id="c" width="500" height="500"></canvas>
<a id="poster" href="#" onclick="PostImageToFacebook(window.authToken)">Post Canvas Image To Facebook</a>
I needed this too, and was not happy with all the code around it because it is lengthy and usually needs jQuery. Here is my code for uploading from Canvas to Facebook:
const dataURItoBlob = (dataURI) => {
let byteString = atob(dataURI.split(',')[1]);
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: 'image/jpeg'
});
}
const upload = async (response) => {
let canvas = document.getElementById('canvas');
let dataURL = canvas.toDataURL('image/jpeg', 1.0);
let blob = dataURItoBlob(dataURL);
let formData = new FormData();
formData.append('access_token', response.authResponse.accessToken);
formData.append('source', blob);
let responseFB = await fetch(`https://graph.facebook.com/me/photos`, {
body: formData,
method: 'post'
});
responseFB = await responseFB.json();
console.log(responseFB);
};
document.getElementById('upload').addEventListener('click', () => {
FB.login((response) => {
//TODO check if user is logged in and authorized publish_actions
upload(response);
}, {scope: 'publish_actions'})
})
Source: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-from-canvas/
Hi I am creating an application where I used ajax request to populate the List of Items.
It works in PC-Browser but not works in iPhone safari.
What could be the issue in safari? Please Help.
createXMLHTTPHandle:function(url,onSuccess,onError){
var xhttp;
try {
if(window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", url, false);
xhttp.setRequestHeader("Content-Type",
"text/xml;charset=utf-8");
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4) {
if(xhttp.status == 200)//clear db and parse
and store new data
{
onSuccess(xhttp.responseText);
}
}
};
xhttp.send();
}
catch(err) {//
if(err=="Error: NETWORK_ERR: XMLHttpRequest Exception 101")
alert("Please check your network connection!");
onError(err);
}
}
Can anyone help me with this code and tell me what is wrong?
My code is not working anymore with the new Facebook API and I am getting the below errors!
Uncaught Error: OAuth2 specification states that 'perms' should now be called
'scope'. Please update.
Error is in http://connect.facebook.net/en_US/all.js line 23
And even if I changed it, it still does not work at all!
//THIS FUNCTION WILL INITIALIZE THE FACEBOOK API AND WILL ADD NEW FACEBOOK ACCOUNTS.
var apikey = $("#apikey").val();
//var tuittingID = $("#tuittingID").val();
FB.init({ apiKey: apikey, status : true, cookie : true, oauth: true });
FB.getLoginStatus(handleSessionResponse);
$('#FBlogin').live('click', function() {
FB.login(handleSessionResponse, {
scope:'manage_pages, publish_stream, offline_access, user_status,
read_insights'
});
return false;
});
function handleSessionResponse(response) {
if (!response.session || String(response.scope) == '') {
return;
}
else
var tuittingID = $.cookie("tuittingID");
$('#AccessToken').val(response.session.access_token);
$("#loader").show();
$.post("tuitting/facebook_lib/fbadd.php",
{ tuittingID: tuittingID, uid: FB.getSession().uid, usid:
FB.getSession().session_key, accesstoken: response.session.access_token },
function(data){
reloadAccounts();
$("#loader").hide();
FB.logout(function(response) {
}); //END LOGOUT FROM FACEBOOK AFTER SUCCESSFULL ACTION
}
); //END AJAX POST FUNCTION DATA
}
Did you make the changes needed to support Oauth 2? it's been mandatory since Oct 1st but the SDKs were only forced onto Oauth 2 yesterday (December 13 2012)
See https://developers.facebook.com/docs/oauth2-https-migration/ - there's a summary of what changed and links to the announcing blog posts - the authentication and javascript docs are the docs you're most likely to need to check if you're making changes as this is where the changes were
We were also affected by this change and we made the following changes to make it work.
FB.init() was required as coded below with oauth set as true.
FB.init({
appId: 1234567890123,
oauth: true
})
And now there is no more session, response.session becomes response.authResponse and response.session.uid becomes response.authResponse.userID
FB.login(function(response) {
if (response.authResponse) {
var postData = {
FBID: response.authResponse.userID,
Access_Token: response.authResponse.accessToken
};
Link with additional information on js changes required
https://developers.facebook.com/blog/post/525/
Also make sure you're using FB.getAuthResponse() instead of FB.getSession().
http://developers.facebook.com/docs/reference/javascript/FB.getAuthResponse/
http://developers.facebook.com/blog/post/525/
This is the Oauth 1.0 code:
html
<div id="fb-root"></div>
<div class="fb-login-button" scope="email,user_birthday"
onlogin="afterFacebookConnect();" autologoutlink="false">Login con Facebook</div>
javascript
window.fbAsyncInit = function () {
FB.init({
appId: 'id_of_app',
status: true,
cookie: true,
xfbml: true });
};
if (document.getElementById('fb-root') != undefined) {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/es_ES/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}
function afterFacebookConnect() {
FB.getLoginStatus(function (response) {
if (response.session) {
window.location = "/facebook/login?token=" + response.session.accessToken;
} else {
// user clicked Cancel
}
});
}
Changes I made to adapt to Oauth 2.0:
window.fbAsyncInit = function () {
FB.init({
appId: 'id_of_app',
status: true,
cookie: true,
xfbml: true,
oauth:true // additional parameter
});
};
function afterFacebookConnect() {
FB.getLoginStatus(function (response) {
if (response.authResponse) {
window.location = "/facebook/login?token="
+ response.authResponse.accessToken;
} else {
// user clicked Cancel
}
});
}
Additional: Here is the code that handles the response (ASP.NET MVC, C#):
using Newtonsoft.Json.Linq;
[RequireHttps]
public ActionResult login(string token)
{
WebClient client = new WebClient();
string JsonResult = client.DownloadString(string.Concat(
"https://graph.facebook.com/me?access_token=", token));
JObject jsonUserInfo = JObject.Parse(JsonResult);
string nombre = jsonUserInfo.Value<string>("first_name");
string segundo_apellido = jsonUserInfo.Value<string>("last_name");
string nombre_completo = jsonUserInfo.Value<string>("name");
string genero = jsonUserInfo.Value<string>("gender");
string email = jsonUserInfo.Value<string>("email");
string birthday = jsonUserInfo.Value<string>("birthday");
// here you do your logic to login the user
// otherwise you can send user to the registration
// form and fill in some data you received from facebook
}