how to share Base 64 image to facebook - javascript

I am trying to share canvas image to Facebook using Graph API.I have to converted it into Base 64 image and upload into Facebook blob storage. All things working fine only when I have to add debugger in code and debug it step by step, but if I have directly click Facebook share button then this not shared on Facebook. Please check following code.
window.fbAsyncInit = function () {
FB.init({
appId: '338935439835732',
xfbml: true,
version: 'v2.8'
});
};
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
$("#btnfacebook").on('click', function () {
debugger;
var data = getCanvas.toDataURL("image/png").replace(/^data:image\/png/, "data:application/octet-stream");
var blob;
try {
var byteString = atob(data.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);
}
blob = new Blob([ab], { type: 'image/png' });
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("source", blob);
fd.append("message", "Photo Text");
FB.login(function () {
var auth = FB.getAuthResponse();
alert(auth.accessToken);
$.ajax({
url: "https://graph.facebook.com/" + auth.userID + "/photos?access_token=" + auth.accessToken,
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data);
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
console.log("Ajax Complete");
}
});
}, { scope: 'publish_actions' });
});
Please help me to find fix

Related

How to use external js script and css for custom dialog box

Could someone help me. Because I'm just started learning JavaScript.
I'm using a custom prompt dialog, before it's working when I use XMLHttpRequest
But, I want to use "Fetch" instead because it's the new one and better.
with using Fetch the dialog is not showing and I'm getting error "layer is not defined"
Here's my little question, How I can call it properly the layer.js and layer.css from the response?
I'm calling it like this (this is a message dialog):
layer.open({
title: "<strong>" + formTitle + "</strong>",
content: "<strong>" + msg + "</strong>",
maxWidth: 500,
});
Here's my code.
!function () {
try {
if (typeof (eval(layer)) == "function") { }
} catch (e) {
var css = 'https://cdn.bootcss.com/layer/3.0.1/skin/default/layer.css';
var js = 'https://cdn.bootcss.com/layer/3.0.1/layer.min.js';
var a = document.createElement("style");
a.type = "text/css";
DownloadStringAsync(css).then(_css => a.innerText = _css);
document.getElementsByTagName("head")[0].appendChild(a)
var a = document.createElement("script");
DownloadStringAsync(js).then(_js => a.text = _js);
document.getElementsByTagName("head")[0].appendChild(a)
}
var url = amp.mediaProxy.facade.config.media.originalSrc;
var title = ampl_title;
var formTitle = "Url Parser v1.0";
var msg = `${title}<br>${GetTitle()}<br>`;
try {
var fileName = `TEST.txt`;
SaveToFileAsync(url, fileName);
} catch (err) {
layer.open({
title: "Error",
content: err.message
});
}
layer.open({
title: "<strong>" + formTitle + "</strong>",
content: "<strong>" + msg + "</strong>",
maxWidth: 500,
});
async function DownloadStringAsync(url) {
let response = await fetch(url, {
method: "GET",
cache: "no-cache",
});
let data = await response.text()
return data;
}
function SaveToFileAsync(url, filename) {
fetch(url, {
method: "GET",
cache: "no-cache",
}).then(async function (t) {
const b = await t.blob();
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
});
}
function GetTitle() {
return document.getElementsByClassName("hero-image-rating eps-line")[0].innerText + "\n";
}
}();

Accessing the Forge Viewer From Two HTML Files

I have been working on a website incorporating the autodesk-forge viewer (more details can be seen on my past questions). I have successfully made many autodesk-forge viewer functions in a standard javascript (.js) file. These functions include displaying the viewer, and isolating to a particular part, when an external button is pressed.
Currently I have a main html/php home page where I have included my javascript file with all my forge functions using <script src="MyForgeFunctions.js"></script>
These functions are accessed through a button, which successfully displays the viewer in the html page. Attached to my main php/html page, another html/php page was added through an iframe html reference (<iframe src="URL.php"></iframe>). My home page displays the main machines we make, while the embedded php/html page displays all the stations within the machine. I have also included the MyForgeFunctions.js inside this second php/html page. Because of the way the website is set up, I need to be able to access the viewer in both web pages. However, when I attempt to access the viewer from the second html page, I get a message that the viewer is undefined. Below is my code from MyForgeFunctions.js.
var ext = '';
var dim = '';
var assemblyname = '';
function getAssemblyName(){
assemblyname = sessionStorage.getItem("assemblyName");
//var ext = partname.substr(partname.lastIndexOf('.'));
ext = assemblyname.split('.');
dim = ext[0] + ':1';
console.log(assemblyname);
console.log(dim);
if (dim !== ''){
isolateSelected();
}
}
//function to get part name from __MachineParts.php
var partname = '';
var extension = '';
var namewithoutextension = '';
function getPartName(){
partname = sessionStorage.getItem("partName");
//var ext = partname.substr(partname.lastIndexOf('.'));
extension = partname.split('.');
namewithoutextension = extension[0] + ':1'
console.log(partname);
console.log(namewithoutextension);
if (namewithoutextension !== ''){
isolateSelectedPart();
}
}
/*******************************************************************************
*
* AUTODESK FORGE VIEWER CODE (HTTP REQUESTS)
*
*******************************************************************************/
//VARIABLE DECLARATION
var code = '';
var access_token = '';
const hub = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const project ='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const folder='xxxxxxxxxxxxxxxxxxxxxxxxx';
const item = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var itemid = '';
var urn = '';
var urn2 = '';
//allow the program to view data from autodesk
function authorize(){
window.location.href = "https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=data:read data:write bucket:read viewables:read bucket:create data:create";
}
//grab the code from the url
function getCode(){
const querystring = window.location.search;
// console.log(querystring);
const urlParams = new URLSearchParams(querystring);
code = urlParams.get('code');
// console.log(code);
}
//call the function to get the code right away, and obtain a token
getCode();
getToken();
//function to obtain access token
function getToken(){
$.ajax({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/gettoken',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
data:'client_id=dm2VLfnwJ6rYHKPAg7dG6l9yVbBQPGlH&client_secret=HRMpOPusLhsVoIMk&grant_type=authorization_code&code=' + code + '&redirect_uri=http://team/__MachineViewerMV.php',
success:function(response){
// console.log(response);
access_token = response.access_token;
console.log(access_token);
}
})
}
//Grab desired file id from project folder
function getItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/* beforeSend:function(before){
if(access_token !== '' && viewer !==''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
function get2dItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/*beforeSend:function(before){
if(access_token !== '' && viewer !== ''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName2d){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName2d){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
//get version of the file using its id
function getVersion(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/items/' + itemid + '/versions',
headers:{
Authorization:'Bearer ' + access_token
},
success:function(response){
//console.log(response);
urn = btoa(response.data[0].relationships.storage.data.id);
console.log(urn);
translateToSVF();
}
})
}
function translateToSVF(){
$.ajax({
method: 'POST',
url:"https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
headers:{
"content-type": "application/json",
Authorization: "Bearer " + access_token
},
data:JSON.stringify({
"input":{ "urn":urn
},
"output": {
"formats": [
{
"type": "svf",
"views": [
"2d",
"3d"
]
}
]
}
}),
success:function(response){
// console.log(response);
urn2 = response.urn;
console.log(urn2);
checkStatus();
}
})
}
function checkStatus(){
$.ajax({
method: 'GET',
url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/" + urn2 + "/manifest",
headers:{
Authorization: "Bearer " + access_token
},
success: function(response){
console.log(response);
if (response.progress == 'complete'){
displayViewer();
}
else if (response.progress !== 'complete'){
alert('File Still Uploading, Press the Display Button Again!');
}
}
})
}
//function to get list of viewables\
var guid = '';
function getViewable(){
$.ajax({
method:'GET',
headers:{
Authorization: "Bearer " + access_token
},
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata',
success:function(response){
console.log(response);
guid = response.data.metadata[0].guid;
console.log(guid);
}
})
}
//funciton to get the list of items within a model
function getTree(){
$.ajax({
method: 'GET',
headers:{
Authorization: "Bearer " + access_token
},
url:'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata/' + guid + '/properties',
success:function(response){
console.log(response);
}
})
}
/**********************************************************************************
*
* FUNCTION TO DISPLAY THE VIEWER IN THE HTML PAGE
*
**********************************************************************************/
var viewer;
function displayViewer(){
//var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = access_token;
console.log(token);
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
// sessionStorage.setItem("viewer", viewer);
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:'+urn2;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
console.log(viewer);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
}
//function to hide the viewer
function destroyViewer(){
console.log(viewer);
viewer.finish();
viewer = null;
Autodesk.Viewing.shutdown();
}
/*****************************************************************************
* FUNCTIONS TO MODIFY THE VIEWER TO ZOOM INTO THE CORRECT PART/ASSEMBLY
*/
function isolateSelected(){
console.log(dim);
console.log(viewer);
viewer.search(dim, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', dim, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
function isolateSelectedPart(){
console.log(namewithoutextension);
viewer.search(namewithoutextension, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', namewithoutextension, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
//function to find the dbid of the part/assembly
function getSubset(dbIds, name, value, callback) {
console.log("getSubset, dbIds.length before = " + dbIds.length)
viewer.model.getBulkProperties(dbIds, {
propFilter: [name],
ignoreHidden: true
}, function(data) {
var newDbIds = []
for (var key in data) {
var item = data[key]
// console.log(item.properties);
if (item.properties[0].displayValue === value) {
newDbIds.push(item.dbId)
}
}
console.log("getSubset, dbIds.length after = " + newDbIds.length)
callback(newDbIds)
}, function(error) {})
}
Because of how the webpage is set up, when I needed to use a variable from the second web page in the first, I used sessionStorage.getItem and sessionStorage.setItem. I have also made a simple function as so inside MyForgeFunctions.js:
function checkViewer(){
console.log(viewer);
}
I then included a button in both html pages to execute the function with an onclick event. When the function is run from the first/home html page the following is displayed:
T {globalManager: e, clientContainer: div#forgeViewer, container: div.adsk-viewing-viewer.notouch.dark-theme.quality-text, config: {…}, contextMenu: o, …}. Which is normal for the viewer, but when the function is executed from the second html page, the viewer is undefined. Any help as to why this is happening or any solutions will be greatly appreciated. Cheers!
From the iframe, in order to access the viewer inside the main web page, I had to use (parent.viewer).

JQuery AJAX function not passing new variable value to global scope

Good afternoon, I am new to programing and have been having problems making a javascript/jquery API call load to a Twitter Tweet. The goal is to be able to hit the Tweet button and send the current quote featured on the page in a Tweet. This is my current attempt on CodePen with the Javascript below;
var counter = 0;
var $body = $('body'),
redVal = 55,
greenVal = 50,
blueVal = 25,
quote;
var sendText = "something current..."; //this is the variable that should be replaced by the API calls and sent to Twitter
//this is Twitter's function to format the page
window.twttr = (function(d, s, id) {
var t, js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
return window.twttr || (t = {
_e: [],
ready: function(f) {
t._e.push(f)
}
});
}(document, "script", "twitter-wjs"));
//the actions to call the quote API
function start() {
redVal = (redVal + 45) % 255;
greenVal = (greenVal + 40) % 255;
blueVal = (blueVal + 20) % 255;
var colorVal = "rgba(" + redVal + "," + greenVal + "," + blueVal + ", 0.4)";
$body.css({"background-color": colorVal });
if (counter % 2 == 0) {
$.ajax({
url: "http://quotes.stormconsultancy.co.uk/quotes/random.json?",
jsonp: "callback",
dataType: "jsonp",
data: {
q: "id, author, quote",
format: "json"
},
success: function( response ) {
var quote = response.quote;
var author = response.author;
document.getElementById("textDisplay").innerHTML = quote;
document.getElementById("author").innerHTML = author;
passText(quote);
}
});
counter += 1;
} else { $.ajax({
url: "http://api.icndb.com/jokes/random?",
jsonp: "callback",
dataType: "jsonp",
success: function( response ) {
var quote = response.value.joke;
var author = " ";
document.getElementById("textDisplay").innerHTML = quote;
document.getElementById("author").innerHTML = author;
passText(quote);
}
});
counter += 1;
}
}
//my attempted helper function to pass the quote values
function passText(superT) {
console.log(superT);
sendText = superT;
return sendText;
}
//the API call to Twitter to send the Tweet
twttr.ready(function (twttr) {
twttr.events.bind('tweet',
twttr.widgets.createShareButton(
'https://dev.twitter.com/',
document.getElementById('container'),
{
text: sendText }
));
})
I think the issue is that the API calls as conducted in the jQuery AJAX script are not being recognized as a reassignment to the quote variable in a way that is accessible outside of the jQuery AJAX call. I read other suggestions ( example ) to try and assign the quote variable from global scope or pass the value through a helper function ( example, as I attempted above…), but both just send the value initially assigned to the quote variable to the Twitter API without the JQuery values.
I hope there is something simple that I don’t know that will get this working. If it is not an issue with the scope of the variable, or if there is a better way to approach this than the JQuery AJAX function I would appreciate any suggestions. Thank you for your time and any help.

How to nested ajax call?

Here is my code.
Currently here every time inner ajax method will call when outer method mark as done.
var folderpath = encodeURIComponent('Recording' + new Date().getTime());
var ajaxWorking = true;
function uploadAudio(mp3Data) {
var reader = new FileReader();
reader.onload = function (event) {
var fd = new FormData();
var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
console.log("mp3name = " + mp3Name);
fd.append('fname', mp3Name);
fd.append('data', event.target.result);
//Costin testing
fd.append('studentId', '1');
fd.append('folderpath', folderpath);
fd.append('recording', stopRecording)
$.ajax({
type: 'POST',
url: '/api/ClientApi/PostRecordedStream',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log(data + " : AjaxDone");
ajaxWorking = false;
}
}).done(function (data) {
console.log(data);
//setTimeout(this, 5000);
console.log(stopRecording + " : " + ajaxWorking);
if (stopRecording == true && ajaxWorking == false) {
console.log(stopRecording + " : " + ajaxWorking + "LoadMP3");
$.ajax({
type: 'GET',
url: '/api/ClientApi/GetAudio',
data: { folderpath: folderpath },
success: function (data) {
console.log(data);
}
}).done(function (data) {
var url = 'data:audio/mp3;base64,' + data;
var li = document.createElement('li');
var au = document.createElement('audio');
var hf = document.createElement('a');
au.controls = true;
au.src = url;
hf.href = url;
hf.download = 'audio_recording_' + new Date().getTime() + '.mp3';
hf.innerHTML = hf.download;
li.appendChild(au);
li.appendChild(hf);
recordingslist.appendChild(li);
});
}
});
};
reader.readAsDataURL(mp3Data);
}
Outer ajax will call multiple time from UI. But I want to call only when all outer ajax call are done.

Facebook photo upload with JavaScript is not working

I need to write a javascript code for construct 2 plugin. below is my code :
Acts.prototype.PublishToWallPHOTO = function (snapshotdata)
{
if (this.runtime.isDomFree || !fbLoggedIn)
return;
var blob;
try
{
blob = dataURItoBlob(snapshotdata.replace("data:image/png;base64,", ""),'image/png');
}
catch(e){console.log(e);}
FB.api('/me/photos', 'POST', {
message:'photo description',
source:blob
}, function(response) {
if (!response || response.error)
console.error(response);
});
};
function dataURItoBlob(dataURI,mime)
{
var byteString = window.atob(dataURI);
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ia], { type: mime });
return blob;
}
for above code parameter for "snapshotdata" look like this : "data:image/png;base64,iVBORw0KGgoAAAA.........."
But my image was not uploaded to facebook using above code. but with same code if I use url:'http://example.com/abc.png' instead of source:blob then it upload a image in given URL successfully. I was tried to find the wrong with above code, but i was unable to find a proper solution. Please tell me if any one know the issue with above code.
ps: sorry for poor English
Maybe a FormData() does the trick.
function uploadPicture(response) {
if (response.status === 'connected') {
var blob = dataURItoBlob(imageHolder.imageElement.dom.src.replace("data:image/png;base64,", ""),'image/png');
var fd = new FormData();
var token = response.authResponse.accessToken;
fd.append("access_token",token);
fd.append("source\"; filename=\"" + "test.png" + "\"", blob);
fd.append("message","Test");
try{
$.ajax({
url:"https://graph.facebook.com/me/photos?access_token=" + token,
type:"POST",
data:fd,
processData:false,
contentType:false,
cache:false,
success:function(data){
console.log("success " + data);
},
error:function(shr,status,data){
console.log("error " + data + " Status " + shr.status);
},
complete:function(){
console.log("Ajax Complete");
}
});
}catch(e){console.log(e);}
}
}

Categories