Get full sized picture from facebook graph API - javascript

I'm using the graph api endpoint /PAGE_ID/posts to get all posts from a facebook page.
Now I want the full sized image from these posts. The picture property of the returned objects gives me only a cropped version of that image.
With the object id from these posts and the API endpoint /OBJECT_ID/picture I get the only the small, normal and album sized version of the picture. But with a little modification to the URL I managed to get the full sized image.
Example
This URL:
https://graph.facebook.com/10152843929471041/picture
redirects to this URL:
https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xpa1/t31.0-8/s720x720/10838228_10152843929471041_5251228402651650719_n.jpg
I removed the 720x720 from that URL to get this URL:
https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xpa1/t31.0-8/s/10838228_10152843929471041_5251228402651650719_n.jpg
which is finally the full sized image.
I think, that I can achieve this modification with a regex pattern. But now is my question, how I can get the URL after the redirect from the original URL (the first one).
Any ideas or simpler solutions?

This is how you can get larger pictures:
/OBJECT-ID/picture?width=500&height=500
Or:
/OBJECT-ID/picture?type=large
Also take a look at answer in this thread: Facebook Graph API : get larger pictures in one request
Edit: As this does not seem to work with Object IDs, you can just grab the image from this response:
https://graph.facebook.com/10152843929471041
Look out for the "images" array.

One can also request the images collection of a photo object, then search for the highest resolution entry.
See documentation. Code:
MyFacebookWrapper.getBestImage = function(photoId) {
var deferred = new $.Deferred();
var params = { fields: "images" };
FB.api("/" + photoId, "get", params,
function (response) {
console.log("MyFacebookWrapper.getBestImage, response:");
console.log(response);
var images = _.sortBy(response.images, 'width');
var best = _.last(images)
deferred.resolve(best);
}
);
return deferred.promise();
};
Usage:
MyFacebookWrapper.getBestImage("photo Id ...").then(function(image) {
console.log(image);
});

Related

Javascript method for getting data based on ID in database table

I'm building an app with many different datasets. Locations, customers, ratings etc...
Throughout the app there are popups and dynamically filled modules, dropdowns etc... At the moment my method is to attach "data-id" as an attribute to any buttons that create dynamic content then run ajax functions using the attribute to get content for the popup.
I'm assuming this is the correct thing to do for large modules that require a lot of dynamic data, but take the below example.
I have a list of locations, when the user clicks (add link) I'd like the popup module to have the title 'Adding link to [location name]'. Would I really need to create an ajax function simply to fill in the name of the location from the database? I could get it from the DOM but that seems silly because most of the popups require data that isn't in the dom.
Basically, my question is; What is the easiest way to get basic data from the database in javascript?
Here's an example of what I have for a whole bunch of buttons with various modules and titles:
$('body').on('click','.add_board_to_loc',function(){
var id = $(this).attr('data-id');
let getLocation = function(id){
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'getLocation',
loc_id: id
},
success: function(data){
$('#add_link_modal_title').text(data['location_name']);
}
});
}
$('#addBoardModal').modal('show');
});
I would split this code into several layers.
One layer can be a transport layer. On transport layer you make ajax request and process errors.
The next layer can be a general layer, here you pass params as table, where statmets and so on. Anyone will be able to access this data through api so be carful with permissions.
And the last layer can be Buisness layer where you request things like: get Location.

Turning API data into HTML

sorry for the newbie question.
I'm new to using API's and I want to take the data from here
https://api.guildwars2.com/v2/commerce/prices/24615 (specifically the unit price under sells:) and display this in HTML.
This project will be using the unit price data across roughly 100 id's and I'd like to organize these numbers and run some basic math with them.
How can I go about this?
fetch('https://api.guildwars2.com/v2/commerce/prices/24615')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
So far I can get the data into the console, but I'm not sure how to turn this into something I can work with.
There is function in jQuery to make API calls, the following code makes you access api data,
$(document).ready( function() {
var info;
var whitelisted;
var quantity;
$.get("https://api.guildwars2.com/v2/commerce/prices/24615",function(obj){
info = obj['id'];
whitelisted = obj["whitlelisted"]
quantity = obj.buys['quantity']
$("#id1").html("id :"+info);
$("#whitelist").html("whitelisted :"+whitelisted);
$("#quan").html("quantity :"+quantity);
});
});
for more info you could look into the following pen link to the code
ignore these jerk moderators.
In your callback function, where you log myJson, edit your previously created html file,
like if you have a div, <div id="myDiv"> </div>, in the response function do something like this
const myDiv = document.getElementById("myDiv")
myDiv.textContent = myJson.name
And your div will show the name from json, or whatever you need. Play around with these ideas and you'll get far

Showing single data field via Google Analytics API

I'm having trouble displaying only a single data field via the Google Analytics API.
For example, how would I display the number of users yesterday? Or the number of users in the past week?
I'm assuming "gapi.analytics.report.Data" is the right constructor. I've tried following the "Data" code in Google's Built-in Components Reference but nothing displays on the front-end.
For the "DataChart" code, there's a "container" option that references the HTML element in the DOM that will correctly display the chart.
This "container" option is missing in "Data" - so how do I display a single data field?
EDIT: Here's the code I'm working with.
You can see a pastebin of my code here: https://pastebin.com/M6U0Bd8B
There's also a live staging version of the site here: http://madebychris.ca/dashboard2.html
The first four section ids are all displaying properly but nothing's showing up for the final <p class ="report">
If you are trying to access the raw data numbers, you can just access the response object:
// Set up the request
var report = new gapi.analytics.report.Data({
query: {
ids: 'ga:XXXX',
metrics: 'ga:sessions',
dimensions: 'ga:city'
}
});
// Define what to do with the response data.
report.on('success', function(response) {
console.log(response);
});
// Run the report
report.execute();
For example, the total's for the metrics is response.totalsForAllResults and the rows for each dimension are held in response.rows
You need to select what you want to do with the variables on the report.on("success", function(response){ function. For example:
report.on('success', function(response) {
$("body > main > div > section:nth-child(4) > h2")[0].innerText =
response.totalsForAllResults["ga:sessions"]
});
report.execute();
Note: You should be able to test on the embedded API demo. Copying and pasting the initial code with the console.log should help show what is going on.

Convert base64 image to file in javascript or how to pass a big base64 string with jquery ajax

This can't take any more of my time. I've tried to solve this a very long time now.
I will give you my whole scenario and then what the problem is.
I have this web site. On one page the user can choose between three image input types.
This is a radio button group:
o Twitter Logo
o Twitter Profile Picture
o Upload picture
If the user choose option 1 or 2, an img tag src is updated with a local-project file (http://localhost:9000/public/images/image.png) and this image src is stored in html5 Web Session Storage variable.
If the user choose option 3 he/she get to choose a file from their computer (a input type="file" appears under the radio group) and the img tag src is updated with this image.
This time, the src that I will store in the session variable won't be a path to the file (which I know is because of security reasons) but the src will be a base64 string. A really big one if the user choose a big image.
So now I have this image stored in the session variable, either a path to the image file included in the project folder or a base64 encoded image.
What I do now is to fetch this value from the session variable in JavaScript. I want to pass this image to my code on the server side. For making an actual image of it and uploading it to places, but that part isnt really necessary.
My problem is that in JavaScript, I can't pass this with a POST using $.ajax.
The base64 string is too big I think, and I can't figure out how I can convert it to something else, say a byte[].
How should I do?
I want to pass this image that the user choose to the server side for further process.
Then on the server side I want to convert it to an actual Image object, or BufferedImage.
Here's a code-block of how it looks now:
function gatherSessionValuesAndGenerateCode(userEmail) {
var email = userEmail;
var category = getSessionValue("category");
var itemName = getSessionValue("itemName");
var service = getSessionValue("service");
var accountName = getSessionValue("accountName");
var action = getSessionValue("action");
var imageType = getSessionValue("imageType");
var imageFile = getSessionValue("imageFile");
var expirationDate = getSessionValue("expirationDate");
$.ajax({
type: "POST",
url: "http://localhost:9000/quikkly/business/create/generate",
data: {
email: email,
category: category,
itemName: itemName,
service: service,
accountName: accountName,
action: action,
imageType: imageType,
imageFile: imageFile, //This is making me feel ill, don't know how to solve it.
expirationDate: expirationDate
},
success: function(response){console.log("Horayyy "+response)}
});
}
ok i got your point but what i am trying to say is may be your string contains 20K characters but i don't think it can be larger than 2-3 Mb and i hope your server settings allows you to post data of size of 2-3 MB.
Apart from this i think putting the image path name in base_64 is not a good idea.If you think someone can steel the data from your seesion then he/she can do any thing with your complete website concept.
Because any how a person can see the image path even when you display some image over web page.
Still if you think you don't want path in seesion you can keep it in some file in key-value pair or you can keep it in database.
OR you can do one more thing just keep the image file name in your seesion data & prepend the exact path when you want to use it internally over server side.

webOS/Ares : read JSON from URL, assign to label

I've used the webOS Ares tool to create a relatively simple App. It displays an image and underneath the image are two labels. One is static, and the other label should be updated with new information by tapping the image.
When I tap the image, I wish to obtain a JSON object via a URL (http://jonathanstark.com/card/api/latest). The typcial JSON that is returned looks like this:
{"balance":{"amount":"0","amount_formatted":"$0.00","balance_id":"28087","created_at":"2011-08-09T12:17:02-0700","message":"My balance is $0.00 as of Aug 9th at 3:17pm EDT (America\/New_York)"}}
I want to parse the JSON's "amount_formatted" field and assign the result to the dynamic label (called cardBalance in main-chrome.js). I know that the JSON should return a single object, per the API.
If that goes well, I will create an additional label and convert/assign the "created_at" field to an additional label, but I want to walk before I run.
I'm having some trouble using AJAX to get the JSON, parse the JSON, and assign a string to one of the labels.
After I get this working, I plan to see if I can load this result on the application's load instead of first requiring the user to tap.
So far, this is my code in the main-assistant.js file. jCard is the image.
Code:
function MainAssistant(argFromPusher) {}
MainAssistant.prototype = {
setup: function() {
Ares.setupSceneAssistant(this);
},
cleanup: function() {
Ares.cleanupSceneAssistant(this);
},
giveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
},
jcardImageTap: function(inSender, event) {
//get "amount_formatted" in JSON from http://jonathanstark.com/card/api/latest
//and assign it to the "updatedBalance" label.
// I need to use Ajax.Request here.
Mojo.Log.info("Requesting latest card balance from Jonathan's Card");
var balanceRequest = new Ajax.Request("http://jonathanstark.com/card/api/latest", {
method: 'get',
evalJSON: 'false',
onSuccess: this.balanceRequestSuccess.bind(this),
onFailure: this.balanceRequestFailure.bind(this)
});
//After I can get the balance working, also get "created_at", parse it, and reformat it in the local time prefs.
},
//Test
balanceRequestSuccess: function(balanceResponse) {
//Chrome says that the page is returning X-JSON.
balanceJSON = balanceResponse.headerJSON;
var balanceAmtFromWeb = balanceJSON.getElementsByTagName("amount_formatted");
Mojo.Log.info(balanceAmtFromWeb[0]);
//The label I wish to update is named "updatedBalance" in main-chrome.js
updatedBalance.label = balanceAmtFromWeb[0];
},
balanceRequestFailure: function(balanceResponse) {
Mojo.Log.info("Failed to get the card balance: " + balanceResponse.getAllHeaders());
Mojo.Log.info(balanceResponse.responseText);
Mojo.Controller.errorDialog("Failed to load the latest card balance.");
},
//End test
btnGiveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
}
};
Here is a screenshot of the application running in the Chrome browser:
In the browser, I get some additional errors that weren't present in the Ares log viewer:
XMLHttpRequest cannot load http://jonathanstark.com/card/api/latest. Origin https://ares.palm.com is not allowed by Access-Control-Allow-Origin.
and
Refused to get unsafe header "X-JSON"
Any assistance is appreciated.
Ajax is the right tool for the job. Since webOS comes packaged with the Prototype library, try using it's Ajax.Request function to do the job. To see some examples of it, you can check out the source code to a webOS app I wrote, Plogger, that accesses Blogger on webOS using Ajax calls. In particular, the source for my post-list-assistant is probably the cleanest to look at to get the idea.
Ajax is pretty much the way you want to get data, even if it sometimes feels like overkill, since it's one of the few ways you can get asynchronous behavior in JavaScript. Otherwise you'd end up with code that hangs the interface while waiting on a response from a server (JavaScript is single threaded).

Categories

Resources