Facebook follow button does not display error message? - facebook

I'm using this https://developers.facebook.com/docs/plugins/follow-button and it's working fine. But what if I enter a facebook url that doesn't exist? It doesn't display any error message and just disappears. I want to display an error message when the user enters a wrong URL. Following is my code:
function wpfollow_func() {
var checkURL = jQuery("#profileCheck").hasClass("has-error");
if (!checkURL) {
var faces = jQuery('#facey').is(':checked');
var layout = jQuery('input[name=layout]:checked').val();
var url = jQuery('#profile').val();
if (url == '' || url == null) {
url = 'https://www.facebook.com/zuck';
}
var token = url.indexOf('http://');
if (token == -1) {
token = url.indexOf('https://');
}
if (token == -1) {
url = 'http://' + url;
}
var data = '<div class="fb-follow" data-href="' + url + '" data-layout="' + layout + '" data-show-faces="' + faces + '"></div>';
console.log(data);
jQuery('.fb-button').html(data);
FB.XFBML.parse();
return false;
}

I hope this is what you are looking for:
FB.XFBML.parse(document.getElementById('some_element'), function() {
alert('I rendered');
});
Following url may help you:
https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse

Related

TypeError: Cannot read property 'getChild' of null - Apps Script

I am a newbie and am trying to use a script to send our school website's feeds
to our Google Chat (Google Workspace for Edu).
I found a code here that works like a charm with the testing Url (https://cloudblog.withgoogle.com/products/gcp/rss/),
but returns me an error when I point to our school's website.
TypeError: Cannot read property 'getChild' of null
Here is the code and below the Debug error
// URL of the RSS feed to parse
var RSS_FEED_URL = "https://www.icriccardomassa.edu.it/agid/feed/";
// https://cloudblog.withgoogle.com/products/gcp/rss/"; <- this works!
// Webhook URL of the Hangouts Chat room
var WEBHOOK_URL = "https://chat.googleapis.com/v1/spaces/AAAAueQ0Yzk/messages?key=AI [..]";
// When DEBUG is set to true, the topic is not actually posted to the room
var DEBUG = false;
function fetchNews() {
var lastUpdate = new Date(PropertiesService.getScriptProperties().getProperty("lastUpdate"));
var lastUpdate = new Date(parseFloat(PropertiesService.getScriptProperties().getProperty("lastUpdate")) || 0);
Logger.log("Last update: " + lastUpdate);
Logger.log("Fetching '" + RSS_FEED_URL + "'...");
var xml = UrlFetchApp.fetch(RSS_FEED_URL).getContentText();
var document = XmlService.parse(xml);
// var items = document.getRootElement().getChild('channel').getChildren('item').reverse();
var items = document.getRootElement().getChild('channel').getChildren('item').reverse();
Logger.log(items.length + " entrie(s) found");
var count = 0;
for (var i = 0; i < items.length; i++) {
var pubDate = new Date(items[i].getChild('pubDate').getText());
var og = items[i].getChild('og');
var title = og.getChild("title").getText();
var description = og.getChild("description").getText();
var link = og.getChild("url").getText();
if(DEBUG){
Logger.log("------ " + (i+1) + "/" + items.length + " ------");
Logger.log(pubDate);
Logger.log(title);
Logger.log(link);
// Logger.log(description);
Logger.log("--------------------");
}
if(pubDate.getTime() > lastUpdate.getTime()) {
Logger.log("Posting topic '"+ title +"'...");
if(!DEBUG){
postTopic_(title, description, link);
}
PropertiesService.getScriptProperties().setProperty("lastUpdate", pubDate.getTime());
count++;
}
}
Logger.log("> " + count + " new(s) posted");
}
function postTopic_(title, description, link) {
var text = "*" + title + "*" + "\n";
if (description){
text += description + "\n";
}
text += link;
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify({
"text": text
})
};
UrlFetchApp.fetch(WEBHOOK_URL, options);
}
Thank you in advance for your help!
Debugger errors

FBgraphapiurl values can't be able access

I have used facebook login in my application, I have used FBgraphapiurl to get the details. But I can't get the birthday, country, state, city. Whereas the firstname,Lastname, email id are coming properly. Here is my code:
var url5 = FBgraphapiurl+'me?fields=id,first_name,last_name,email,gender&access_token=' + fbcodessss + '&redirect_uri=http://www.fastabuy.com/index.php';
Ext.Ajax.request({
url: url5,
success: function (data, status) {
var jsondata = eval("(" + data.responseText + ")");
var data = jsondata;
var id = data.id;
var email = data.email;
var name = data.first_name;
if (data.id != null) {
App.gvars.BuyFBID = data.id;
}
if (data.first_name != null) {
Ext.getCmp('firstname').setValue(data.first_name);
Ext.getCmp('lastname').setValue(data.last_name);
}
if (data.email != null) {
Ext.getCmp('emailId').setValue(data.email);
Ext.getCmp('Gender').setValue(data.gender);
}
}
})}});
When I try with the following:
var url5 = FBgraphapiurl+'me?fields=id,first_name,last_name,email,gender,birthdate,country,state&access_token=' + fbcodessss + '&redirect_uri=http://www.fastabuy.com/index.php';
What change required to get the country, city, state? Whats wrong with my code?

Can't Post facebook URL using facebook SDK

I have a webapplication that I use to reshare existing post as follow
1)get the post details using https://graph.facebook.com/UserID_postID?access_token=AAA (works fine)
2)fill the a data of the new post from the old one and try to resend it but there is some strange behviour
if I use
oldpost.link = newpost.link it doesnt nothing appear on the wall but if I used
oldpost.link="\""newpost.link+"\"" works and the post appear on facebook wall but the link appears corputted as invalid.invalid/
function getPost(userID, postID, token) {
jQuery.getJSON("https://graph.facebook.com/" + userID + "_" + postID + "?access_token=" + token, function (post) {
here is the code any idea please
var newPost = {};
newPost.message = "hi";
if (post.link != "" && post.link != null && post.link != "undefined") {
newPost.link = "\"" + post.link + "\"";
}
if (post.name != "" && post.name != null && post.name != "undefined") {
newPost.name = "\"" + post.name + "\"";
}
if (post.picture != "" && post.picture != null && post.picture != "undefined") {
newPost.picture = "\"" + post.picture + "\"";
}
if (post.description != "" && post.description != null && post.description != "undefined") {
newPost.description = "\"" + post.description + "\"";
}
doPost(newPost);
});
}
function doPost(newPost) {
FB.api('/me/feed', 'post',
newPost, function (response) {
if (!response || response.error) {
alert(' Denied Access');
} else {
alert('Success');
}
});
}

Facebook FQL page_user

Right i have a problem which i have done so much research for that i still cant be able to solve the problem. What i am trying to achieve is when a facebook user LIKES my page not an app, i want to be able to retrieve all the users that have liked the facebook page.
I am using FQL but having no luck at all, if i do an FQL based on the admins of the page it brings the data up.
SELECT first_name, last_name FROM user WHERE uid IN (SELECT uid FROM page_fan WHERE page_id = [your page id])
the above FQL should work. But nothing is being displayed, is this a facebook bug that has not been flagged or fixed?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCFacebookTestApp.Models;
using Facebook;
using Facebook.Web;
namespace MVCFacebookTestApp.Controllers
{
public class HomeController : Controller
{
public FacebookSession FacebookSession
{
get { return (FacebookWebContext.Current.Session); }
}
public ActionResult Index()
{
string request = Request.Form["signed_request"];
string accessToken = "";
if (Request.Form["access_token"] != null)
{
accessToken = Request.Form["access_token"];
}
FacebookApplication app = new FacebookApplication();
FacebookSignedRequest result = FacebookSignedRequest.Parse(app.InnerCurrent, request);
if (String.IsNullOrWhiteSpace(accessToken))
{
accessToken = result.AccessToken;
}
dynamic data = result.Data;
bool liked = data.page.liked;
//bool liked = true;
if (!liked)
{
Home h = Home.NotLiked();
return View(h);
}
else
{
Home h = Home.Liked();
FacebookWebClient fb = null;
if (String.IsNullOrWhiteSpace(accessToken))
{
var fbRequest = FacebookWebContext.Current;
if (fbRequest.IsAuthorized())
fb = new FacebookWebClient(fbRequest);
}
else
{
fb = new FacebookWebClient(accessToken);
}
if (fb != null)
{
dynamic r = fb.Get("/me");
h.TestString2 += " Ha! We captured this data about you!";
h.TestString2 += " Name: " + r.name;
h.TestString2 += " Location: " + r.location;
h.TestString2 += " Birthday: " + r.birthday;
h.TestString2 += " About Me: " + r.aboutme;
h.ImgUrl = "http://graph.facebook.com/" + r.id + "/picture?type=large";
string fqlResult = "";
var fbApp = new FacebookClient(accessToken);
//basic fql query execution
dynamic friends = fbApp.Query("SELECT uid FROM page_admin WHERE page_id='160828267335555'");
//SELECT uid FROM page_fan WHERE page_id = 160828267335555
//"SELECT uid FROM page_fan WHERE uid=me() AND page_id=<your page id>";
//loop through all friends and get their name and create response containing friends' name and profile picture
foreach (dynamic friend in friends)
{
fqlResult += friend.uid + "<br />";
//fqlResult += friend.name + "<img src='" + friend.pic_square + "' alt='" + friend.name + "' /><br />";
}
ViewBag.Likes = fqlResult;
}
else
{
//Display a message saying not authed....
}
return View(h);
}
}
}
}
is there a solution out there that actually works? Please do get back to me ASAP your help would be much appreciated, will save me from losing all my hair with the stress LOL
Thanks in advance.
You can make a GET request to /USER_ID/likes/PAGE_ID (replacing the caps part with the relevant IDs) to check if a particular user is a fan of your page. This is the replacement for the old 'pages.isFan' API method.
There's no way to retrieve a list of users that like your page.

Use currentLocation along with a business search in bing map API

I was currently at this site which shows how to implement business search using the bing map api. But what I am trying to implement is, first the map should get your current location and search for type of business nearby, let's say Restaurant or Check Cashing place.
My current page has the current location working but now how I implement the FindNearBy function with my page?
P.s. I want the search to already take place for the user without having to enter a search text, so the map should load up with current location and right next to it should list all or maybe the closest 5 restaurant nearby.
Not with Bing Maps...you need the Bing Phonebook API to do this.
I can get you part of the way there. The below example combines the use of both the Bing Maps API and the Bing Phonebook API) I just submitted a similar question about how to find the type of business, however...I'm not sure there's a wayto do this :/ (Below example searches for all Starbucks in the area ...of course, some HTML integration is required.
var _map;
var _appId;
$(document).ready(function () {
if (Modernizr.geolocation) {
$(".geofallback").hide();
}
else {
$(".geofallback").show();
}
$.post("Home/GetBingMapsKey", { "func": "GetBingMapsKey" }, function (data) {
// Create a Bing map
_map = new Microsoft.Maps.Map(document.getElementById("map"),
{ credentials: data }); //, mapTypeId: Microsoft.Maps.MapTypeId.ordnanceSurvey
});
// Get the current position from the browser
if (!navigator.geolocation) {
$("#results").html("This browser doesn't support geolocation, please enter an address");
}
else {
$.post("Home/GetBingKey", { "func": "GetBingKey" }, function (data) {
_appId = data;
});
navigator.geolocation.getCurrentPosition(onPositionReady, onError);
navigator.geolocation.getCurrentPosition(Search, onError);
}
});
function onPositionReady(position) {
// Apply the position to the map
var location = new Microsoft.Maps.Location(position.coords.latitude,
position.coords.longitude);
_map.setView({ zoom: 18, center: location });
// Add a pushpin to the map representing the current location
var pin = new Microsoft.Maps.Pushpin(location);
_map.entities.push(pin);
}
function onError(err) {
switch (err.code) {
case 0:
alert("Unknown error :(");
break;
case 1:
alert("Location services are unavailable per your request.");
break;
case 2:
alert("Location data is unavailable.");
break;
case 3:
alert("The location request has timed out. Please contact support if you continue to experience issues.");
break;
}
}
function Search(position) {
// note a bunch of this code uses the example code from
// Microsoft for the Phonebook API
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + _appId
+ "&Query=starbucks"
+ "&Sources=Phonebook"
// Common request fields (optional)
+ "&Version=2.2"
+ "&Market=en-us"
+ "&UILanguage=en"
+ "&Latitude=" + position.coords.latitude
+ "&Longitude=" + position.coords.longitude
+ "&Radius=100.0"
+ "&Options=EnableHighlighting"
// Phonebook-specific request fields (optional)
// Phonebook.Count max val is 25
+ "&Phonebook.Count=25"
+ "&Phonebook.Offset=0"
// YP = Commercial Entity, WP = Residential
+ "&Phonebook.FileType=YP"
+ "&Phonebook.SortBy=Distance"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=?";
$.getJSON(requestStr, function (data) {
SearchCompleted(data);
});
}
function FormatBingQuery(appId, latitude ) {
}
function SearchCompleted(response) {
var errors = response.SearchResponse.Errors;
if (errors != null) {
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else {
// There were no errors in the response. Display the
// Phonebook results.
DisplayResults(response);
}
}
function DisplayResults(response) {
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Phonebook.Results;
// Display the results header.
resultsHeader.innerHTML = "Bing API Version "
+ response.SearchResponse.Version
+ "<br />Phonebook results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Phonebook.Offset + 1)
+ " to "
+ (response.SearchResponse.Phonebook.Offset + results.length)
+ " of "
+ response.SearchResponse.Phonebook.Total
+ " results<br />";
// Display the Phonebook results.
var resultsListItem = null;
var resultStr = "";
for (var i = 0; i < results.length; ++i) {
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
//loc is specific to my C# object
var loc = new Array();
loc[0] = results[i].Longitude;
loc[1] = results[i].Latitude;
var address = {
AddressLine1: results[i].Address,
City: results[i].City,
State: results[i].StateOrProvince,
PostalCode: results[i].PostalCode,
Latitude: results[i].Latitude,
Longitude: results[i].Longitude,
Country: results[i].CountryOrRegion,
ID: results[i].UniqueId
};
//this part is specific to my project to return the
//address results so I can store them (since my
//implementation is a demonstration of how to
//use the MongoDB geoNear() functionality
$.ajax({
url: "/Home/AddAddressToCollection",
type: 'post',
data: JSON.stringify(address),
contentType: 'application/json',
dataType: 'json'
});
resultStr = results[i].Business
+ "<br />"
+ results[i].Address
+ "<br />"
+ results[i].City
+ ", "
+ results[i].StateOrProvince
+ "<br />"
+ results[i].PhoneNumber
+ "<br />Average Rating: "
+ results[i].UserRating
+ "<br /><br />";
// Replace highlighting characters with strong tags.
resultsListItem.innerHTML = ReplaceHighlightingCharacters(
resultStr,
"<strong>",
"</strong>");
}
}
function ReplaceHighlightingCharacters(text, beginStr, endStr) {
// Replace all occurrences of U+E000 (begin highlighting) with
// beginStr. Replace all occurrences of U+E001 (end highlighting)
// with endStr.
var regexBegin = new RegExp("\uE000", "g");
var regexEnd = new RegExp("\uE001", "g");
return text.replace(regexBegin, beginStr).replace(regexEnd, endStr);
}
function DisplayErrors(errors) {
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i) {
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i]) {
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
// Bonus: In case you want to provide directions
// for how to get to a selected entity
// _map.getCredentials(function (credentials) {
// $.getJSON('http://dev.virtualearth.net/REST/V1/Routes/driving?' + 'wp.0=' + lat1 + ',' + lon1 + '&wp.1=' + lat2 + ',' + lon2 + '&distanceUnit=mi&optmz=distance&key=' + credentials + '&jsonp=?&s=1',
// function (result) {
// if (result.resourceSets[0].estimatedTotal > 0) {
// var distance = result.resourceSets[0].resources[0].travelDistance;
// }
// else {
// $("#results").html("Oops! It appears one or more of the addresses you entered are incorrect. :( ");
// }
// });
// });
//Tie into a function that shows an input field
//for use as a fallback in case cannot use HTML5 geoLocation
//$(document).ready(function () {
// $("#btnFindLocation").click(function () {
// //check user has entered something first
// if ($("#txtAddress").val().length > 0) {
// //send location query to bing maps REST api
// _map.getCredentials(function (credentials) {
// $.getJSON('http://dev.virtualearth.net/REST/v1/Locations?query=' + $("#txtAddress").val() + '&key=' + credentials + '&jsonp=?&s=1',
// function (result) {
// if (result.resourceSets[0].estimatedTotal > 0) {
// var loc = result.resourceSets[0].resources[0].point.coordinates;
// $("#lat").val(loc[0]);
// $("#lon").val(loc[1]);
// var location = new Microsoft.Maps.Location(loc[0],
// loc[1]);
// _map.setView({ zoom: 18, center: location });
// // Add a pushpin to the map representing the current location
// var pin = new Microsoft.Maps.Pushpin(location);
// _map.entities.push(pin);
// }
// else {
// $("#results").html("sorry that address cannot be found");
// }
// });
// });
// }
// else {
// $("#results").html("please enter an address");
// }
// });
//});