I am using facebook's graph api Version 3.1.1
It is working fine but the logout url is not working properly.
With the logout url it is being logged out from the facebook but it is not being logged out in my application. Strange but true.
I am pasting necessary snipet from the code.
index.php
<script type="text/javascript">
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt) {
FB.ui({method: 'feed',
message: userPrompt,
link: hrefLink,
caption: hrefTitle,
picture: ''
});
//http://developers.facebook.com/docs/reference/dialogs/feed/
}
function publishStream() {
streamPublish("Stream Publish", 'Checkout personalized products at www.picpixa.com. I found some of them are just awesome!', 'Checkout www.picpixa.com', 'http://www.picpixa.com', "Personalized Products");
}
</script>
<style type="text/css">
.box{
margin: 5px;
border: 1px solid #60729b;
padding: 5px;
width: 500px;
height: 200px;
overflow:auto;
background-color: #e6ebf8;
}
</style>
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId: '',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
</script>
<body>
<div id="load" class="loader"></div>
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="modal-footer">
<?php
echo "User: $user";
if (!$user) { ?>
<h1>You have to login using Facebook Login Button to see your uploaded images.</h1>
<a class='btn btn-primary' href="<?= $loginUrl ?>" onClick='loader()'><img src="Images/login.png"></a>
<?php } else { ?>
<a class='btn btn-primary' href="<?= $logoutUrl ?>" onClick='loader()'><img src="Images/logout.png"></a>
<?php } ?>
</div>
basefacebook.php
public function getLogoutUrl($params = array()) {
return $this->getUrl(
'www', 'logout.php', array_merge(array(
'next' => $this->getCurrentUrl(),
'access_token' => $this->getAccessToken(),
), $params)
);
}
Feel free to ask for more info.
Please help me out with this.
Thank you,
Related
I need some help with my code as I have got a problem with defined the variable to post them in Ajax. I am working on PHP as I am fetching the data from mysql database to input the information in PHP, so I would like to post the ID in ajax.
I have defined the variable $autoid outside of the while loop, but I am unable to defined them when I am using jquery because it will show empty data when I try to post them in Ajax.
When I try this:
var ID = $(this).data('deleteid');
$.ajax({
type: 'POST',
url: "sendtest.php",
data: {ID : "deleteid"
},
success: function(resultData) {
alert(resultData)
}
Here is the full code:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
else
{
$link = mysqli_connect('localhost', 'mydbusername', 'mydbpassword', 'mydbpassword');
$param_username = $_SESSION['username'];
$autocampaign = $_SESSION["auto_campaign"];
$autor_sql = "SELECT id, subject, day_cycle, enabled, delaysend FROM auto WHERE campaign ='$autocampaign' AND username ='$param_username'";
$autoid = '';
$results = mysqli_query($link, $auto_sql);
if (mysqli_num_rows($results) > 0)
{
while ($row = mysqli_fetch_array($results))
{
$autoid = $row["id"];
$autosubject = $row["subject"];
$autodaycycle = $row["day_cycle"];
$autoenabled = $row["enabled"];
$autodelay = $row["delaysend"];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
.calendar-content {
float: left;
width: 100%;
min-height: 112px;
border: 1px solid #ccc;
position: relative;
margin-top: -1px;
}
</style>
<div class="calendar-content">
<div style="margin-left: 40px;margin-top: 20px; height: 40px;">
<span id="autosubject" style="font-size: 25px;color: #0c7ac0;float: left;">Subject: <?php echo $autosubject ?> </span><br>
<div style="margin-left: 35px; margin-top: 15px; height: 40px;">
<form action="" method="post">
<span style="font-size: 15px; color: #ccd5d9; float: left; margin-top: -1px"><a name="autoid" id="autoid" href="#contactModal" role="button" data-toggle="modal">Send a test</a> | <a name="deleteid" id="deleteid" href="/auto/delete_auto.php?id=<?php echo $autoid; ?>"> Delete </a> | Copy to Draft | Settings</span>
</form>
</div>
</div><br>
<!-- email Modal -->
<div id="contactModal" class="modal fade" style="margin-top: 12%;" tabindex="-1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="height: 250px;">
<div class="modal-header" style="margin-bottom: 10px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Send A Test Email</h3>
</div>
<div class="modal-body" style="height: 65%;">
<form action="" method="post">
<label class="label-control" value="">Send test message to email address:</label>
<select name="emails" id="emails" value="" style="width: 400px; margin-top: 10px; margin-bottom: 18px; margin-left: 60px;">
<option selected="selected" value='title'>Title</option>";
</select><br>
<button name="send_email" id="send_email" type="submit" class="btn btn-primary" style="margin-left: 36%;" data-auto-id="<?php echo $autoid; ?>">Send Test</button>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#send_email').click(function(e) {
$(this)
.html("<span><i class='fa fa-spinner fa-spin'></i> Sending...</span>")
.prop("disabled", true);
var ID = $(this).data('deleteid');
$.ajax({
type: 'POST',
url: "sendtest.php",
data: {ID : "deleteid"
},
success: function(resultData) {
alert(resultData)
$('#contactModal').modal('hide');
$("#send_email")
.html("Send Test")
.prop("disabled", false);
}
});
});
});
</script>
<?php
}
?>
Here is the sendtest.php:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
else if(isset($_POST))
{
$id = $_POST[$autoid];
echo "hello your id is...";
echo $id;
}
?>
What I want to achieve is when I click on a send a test hyperlink, a modal will display and when I click on a button after I select on a dropdown listbox, I want to fetch the ID from the Delete hyperlink so I can post them in ajax. The reasons I want to post the ID in ajax is because I want to stay on the same page while I want to fetch the information from the mysql database.
Can you please show me an example how I can fetch the ID from the Delete hyperlink to post them in ajax?
Thank you for understanding what I am trying to do.
There are several issues in your code:
1st: data: {ID : "deleteid"}, should be data: {ID : ID }, (you want to send the var, not the string "deleteid")
2nd: var ID = $(this).data('deleteid'); should be var ID = $(this).data('auto-id');, because the data-attribute is data-auto-id="...
3rd: $id = $_POST[$autoid]; will throw an error (undefined variable) & a notice (undefined index). Should be $id = $_POST['ID'], because you call the param "ID" here: data: {ID : varname},
4th: you are missing a ; here: alert(resultData)
Here's the corrected ajax-part:
var ID = $(this).data('auto-id');
$.ajax({
type: 'POST',
url: "sendtest.php",
data: {ID : ID },
success: function(resultData) {
alert(resultData);
$('#contactModal').modal('hide');
$("#send_email")
.html("Send Test")
.prop("disabled", false);
}
});
Please have a look at the below CakePHP code
Flip2.php (Model)
<?php
class Flip2 extends AppModel {
var $name = 'Flip2';
public $useTable = false;
//Increment the correct_answer field of the specific user
public function correctAnswer($userID=89, $word)
{
$setQuery = "UPDATE `users_words` SET `correctanswer` = `correctanswer`+1 WHERE `userid`=$userID && `wordid`='$word' ";
query($setQuery);
}
}
Flip2Controller.php (Controller)
<?php
class Flip2Controller extends AppController {
public function index()
{
}
}
?>
index.ctp (View)
<?php
//echo $this->Html->css(array('bootstrap', 'mark', 'style'));
echo $this->Html->script(array('timer','swfobject','bootstrap.min.js'));
?>
<style>
#hideall {
display: none;
opacity: 0.7;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
border: 1px solid #cecece;
z-index: 1;
vertical-align:middle;
text-align:center;
}
.removeCardflip{
transition: rotateY(0deg);
-webkit-transition: rotateY(0deg);
transition-duration: 0s;
}
/* SECTIONS */
.section {
clear: both;
padding: 0 10px 0 10px;
margin: 0px;
}
</style>
<div id="hideall">
<?php //echo $this->Html->image('progress.gif', array('alt' => 'Wait', 'style' => 'text-align:center; padding-top:200px;'));?>
</div>
<!--<div class="wrapper" style="border: 1px solid red; width: 100%;">-->
<div class="section group" style="margin-top: 50px;">
<div class="col span_3_of_3">
<h3 style="margin:0px; font-size:22px;">Play word game: </h3>
</div>
</div>
<div class="">
<div>
<div>
<span class="remainWords"><?php //echo count($words);?></span> oxxxxxxxxxxxxxxxf <?php //echo $totalWords;?>
</div>
<div>
<?php
echo $this->Html->image("comic_edit.png",
array(
"alt" => "Pareto List",
"id" => "paretoList",
'url' => "javascript:;"
)
);
?>
</div>
</div>
</div>
<div class="container"><div class="row">
<?php
foreach($worddeck as $worcard)
{
?>
<div class="xy col-lg-3 col-md-4 col-sm-6 img-rounded" id="card1" style="width:250px; height:200px; background-color:grey; heiht:170px; margin: 10px 10px;">
<div id="enside1" >
<h1 data-pos="<?php //echo ; ?>" ><?php echo $worcard['unique_wordsforcards']['en_word']; $enSpell = $worcard['unique_wordsforcards']['en_word']; ?></h1>
</div>
<div id="ptside1" style="display:none;">
<?php echo $phonemer[$enSpell]; ?>
<p><?php echo $worcard['unique_wordsforcards']['hint']; ?></p>
</div>
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
</div>
<?php
}
?>
</div></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function(){
$( ".btn-danger" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".xy" ).click(function(){
$(this).find("#enside1").toggle();
$(this).find("#ptside1").toggle();
console.log(this);
});
});
</script>
Now, what I need to do is, this. When the user click on the Acertei button, I need to execute the function correctAnswer. I am very new to PHP and CakePHP so I am really confused about how to do this when a button is clicked. Any advice please?
You have
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
You should use different IDs for each button.
You can call the correctAnswer function with ajax:
Change the button to something like
<button type="button" id="2" data-word="<?php $worcard['unique_wordsforcards']['en_word'] ?>" class="a btn btn-success mr5 btn-lg">Acertei</button>
And then add the following code in $(document).ready()
$(document).ready(function(){
$(".btn-success").click(function(){
var word = $(this).data('word');
$.post('/flip2/correct.json', { word: word })
.done(function(data) {
alert('Saved');
});
I am not sure how the user part works. You should probably have that in the session, and not sent to the function. I hardcoded user 89 and added a way for you to send the word.
Use an appropriate model method
The function correctAnswer in the model would better be written using updateAll:
public function correctAnswer($userId, $word) {
return $this->updateAll(
array('correctanswer' => 'correctanswer + 1'),
array(
'userid' => $userId,
'wordid' => $word
)
);
}
Written in this way the inputs ($userId and $word) will be escaped appropriately and not susceptible to sql injection.
Create a controller action
The doorway to the web for an application is a controller action, create a simple function, calling the model method, and write it to output json:
public function correct() {
$postData = $this->request->data;
$word = $this->request->data['word'];
$userId = $this->Auth->user('id');
$result = false;
if ($userId && $word) {
$result = $this->Flip2->correctAnswer($userId, $word);
}
$this->set('_serialize', array('result'));
$this->set('result', $result);
}
Note that
It'll only work via a post request.
The Auth component (the session) is used to get the current user id, it's not a user-defined input.
This function is defined such that it'll work as a json response.
There's no need to create a view file with the above code.
Be sure to setup your app to handle json requests:
After adding Router::parseExtensions('json'); to your routes file, CakePHP will automatically switch view classes when a request is done with the .json extension, or the Accept header is application/json.
Call the controller action
The required js would be of the form:
$(".btn-success").click(function(){
var word = ...;
$.post(
'/flip2/correct.json',
{word: word},
function (data) {
console.log(data);
// {result: bool}
}
);
});
Note that:
The url ends in .json which is a simple and robust way to provoke CakePHP to respond as json.
It is a post request.
The response will be of the form defined by _serializein the controller action.
I have created an api to import photos from facebook and google+. But I am facing a problem in displaying the list of photos. Can you please resolve this?
My Code Below:
File Name: index.php (Google)
<?php
include_once "google-plus-access.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Google+ API To Fetch Photos</title>
<link rel='stylesheet' href='style.css' />
</head>
<body>
<div id="bar">
<div class="top-area" >
<div class="login" >
<?php if(isset($me) && isset($activities)) { ?>
<a href="?logout" ><h5>Logout</h5></a>
<?php } else { ?>
<a href="<?php echo($authUrl); ?>" ><h5>Login</h5></a>
<?php } ?>
</div>
</div>
</div>
<?php if(isset($me) && isset($activities)) {?>
<div class="big-container" >
<div class="profile" >
<div class="profile-pic" ><a href="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>" ><img src="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>?sz=200" /></a>
</div>
<div class="profile-info" >
<div class="name" ><a href="<?php echo($me['url']) ; ?>" ><?php if(isset($me['displayName'])) echo(strtoupper($me['displayName'])); else echo "Not set or private"; ?></a></div>
<div class="details" >
<ul>
<li><b>GENDER : </b><?php if(isset($me['gender'])) echo($me['gender']); else echo "Not set or private"; ?></li>
<li><b>ORGANISATION : </b><?php if(isset($me['organizations']['0']['name'])) echo($me['organizations']['0']['name']); else echo "Not set or private"; ?></li>
<li><b>PLACE : </b><?php if(isset($me['placesLived']['0']['value'])) echo($me['placesLived']['0']['value']); else echo "Not set or private"; ?></li>
</ul>
</div>
</div>
</div>
</div>
<?php foreach($activities['items'] as $activity): ?>
<div class="activity" >
<div class="title" ><a href="<?php echo($activity['object']['url']) ; ?>" ><?php echo($activity['object']['content']); ?></a></div>
<p>Published at <?php echo($activity['published']); ?></p>
<p>
<?php echo($activity['object']['replies']['totalItems']); ?> Replies .
<?php echo($activity['object']['plusoners']['totalItems']); ?> Plusoners .
<?php echo($activity['object']['resharers']['totalItems']); ?> Reshares
</p>
</div>
<?php endforeach ?>
<br><br>
<div class="photos">
<?php
if(isset($me['url']))
{
$photos = "https://plus.google.com/photos/";//.$me['id']."/albums";
echo $photos;
}
?>
</div>
<?php } else {?>
<div class="login-box">
<div id="connect-button"><a href="<?php echo($authUrl); ?>" ><img src="connect-button.png" alt="Connect to your Google+ Account"/></a>
<div>This API is purely read-only. It will <b>NOT</b> post anything to your profile.
</div>
</div>
</div>
<?php } ?>
</body>
</html>
File Name: google-plus-access.php
<?php
require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiPlusService.php';
session_start();
$client = new apiClient();
$client->setApplicationName("picpixa");
//*********** Replace with Your API Credentials **************
$client->setClientId('***********************');
$client->setClientSecret('************************');
$client->setRedirectUri('http://localhost/MyApi/Google-Plus/');
$client->setDeveloperKey('*********************************');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me','https://www.googleapis.com/auth/photos'));
$plus = new apiPlusService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>
File Name: index.php (Facebook)
<?php
include_once "fbmain.php";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Fetch Image From Facebook</title>
<script type="text/javascript">
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt) {
FB.ui({method: 'feed',
message: userPrompt,
link: hrefLink,
caption: hrefTitle,
picture: 'http://thinkdiff.net/ithinkdiff.png'
});
//http://developers.facebook.com/docs/reference/dialogs/feed/
}
function publishStream() {
streamPublish("Stream Publish", 'Checkout personalized products at www.picpixa.com. I found some of them are just awesome!', 'Checkout www.picpixa.com', 'http://www.picpixa.com', "Personalized Products");
}
function newInvite() {
var receiverUserIds = FB.ui({
method: 'apprequests',
message: 'Come on checkout Personalized Products. visit http://www.picpixa.com',
},
function(receiverUserIds) {
console.log("IDS : " + receiverUserIds.request_ids);
});
//http://developers.facebook.com/docs/reference/dialogs/requests/
}
</script>
</head>
<body>
<style type="text/css">
.box{
margin: 5px;
border: 1px solid #60729b;
padding: 5px;
width: 500px;
height: 200px;
overflow:auto;
background-color: #e6ebf8;
}
</style>
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId: '<?= $fbconfig['appid'] ?>',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
</script>
<?php if (!$user) { ?>
You have to login using Facebook Login Button to see api calling result.
<img src="Images/login.png">
<?php } else { ?>
<img src="Images/logout.png">
<?php } ?>
<!-- all time check if user session is valid or not -->
<?php if ($user) { ?>
<table border="0" cellspacing="3" cellpadding="3">
<tr>
<td>
<!-- Data retrived from user profile are shown here -->
<div class="box">
<b>User Photos using Graph API</b>
<?php d($user_photos); ?>
</div>
</td>
</tr>
</table>
<?php }?>
</body>
</html>
File Name: fbmain.php
<?php
$fbconfig['appid'] = "Your App Id";
$fbconfig['secret'] = "Your App Secret";
$fbconfig['baseurl'] = "localhost/MyApi/Facebook/index.php";
//
if (isset($_GET['request_ids'])) {
//user comes from invitation
//track them if you need
}
try {
include_once "facebook.php";
} catch (Exception $o) {
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => false,
));
//Facebook Authentication part
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'user_photos',
'redirect_uri' => $fbconfig['baseurl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
//if user is logged in and session is valid.
if ($user) {
//Retriving photos of user using graph api
try {
$user_photos = $facebook->api("/$user/photos");
} catch (Exception $o) {
d($o);
}
}
function d($d) {
echo 'This function is called <br><br><pre>';
print_r($d);
echo '</pre>';
}
?>
I am not sure what you expected on the Google+ side. All you are doing for photos, apparently, is printing the URL based on the Google ID. (Assuming the portion that was commented out.)
There is no way using the Google+ API to get the user's photos. You need to look into using the Picasa Web Albums Data API, but this is using Google's older GData protocol. There are a couple of resources that may help, for example, there is a PHP library which uses an older version of the protocol and a more modern example code snippet which may guide you in doing this.
You should star https://code.google.com/p/google-plus-platform/issues/detail?id=670 to indicate you want a more modern API for photos in Google+.
I want to share my website articles on facebook (content,image,title)!
but facebook doesn't detect correct image.
in this case I put an static image URL.
this is my code:
<li>
<a id="buttton" href="http://www.facebook.com/sharer.php?s=100&p[title]=<?php echo $title;?>&p[summary]=<?php echo $summary;?>&p[url]=<?php echo urlencode($url);?>&p[images][0]=http://www.example.com/images/report/daily_report/KNDR/image(2).jpg" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600'); return false;">
<img src="<?php echo base_url()?>media/images/share.png" alt=""/>
</a>
</li>
You can use facebook javascript sdk. First add FB Js SDK to your code (please refer to https://developers.facebook.com/docs/javascript)
window.fbAsyncInit = function(){
FB.init({
appId: 'xxxxx', status: true, cookie: true, xfbml: true });
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if(d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id;
js.async = true;js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}
So when you want to share something
Share
And finally JS to handle click:
$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));
return false;
});
This solution is using javascript to open a new window when a user clicks on your custom share button.
HTML:
<a href="#" onclick="share_fb('http://urlhere.com/test/55d7258b61707022e3050000');return false;" rel="nofollow" share_url="http://urlhere.com/test/55d7258b61707022e3050000" target="_blank">
//using fontawesome
<i class="uk-icon-facebook uk-float-left"></i>
Share
</a>
and in your javascript file. note window.open params are (url, dialogue title, width, height)
function share_fb(url) {
window.open('https://www.facebook.com/sharer/sharer.php?u='+url,'facebook-share-dialog',"width=626, height=436")
}
Well, I use this method on my site:
<a class="share-btn" href="https://www.facebook.com/sharer/sharer.php?app_id=[your_app_id]&sdk=joey&u=[full_article_url]&display=popup&ref=plugin&src=share_button" onclick="return !window.open(this.href, 'Facebook', 'width=640,height=580')">
Works perfectly.
The best way is to use your code and then store the image in OG tags in the page you are linking to, then Facebook will pick them up.
<meta property="og:title" content="Facebook Open Graph Demo">
<meta property="og:image" content="http://example.com/main-image.png">
<meta property="og:site_name" content="Example Website">
<meta property="og:description" content="Here is a nice description">
You can find documentation to OG tags and how to use them with share buttons here
Given that we are in a php code context and the variable $url contains the link the user wants to share, you can try this to use a custom image :
<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"><img src="/img/facebook-share-button.png" /></a>
or this for just plain text :
<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank">share</a>
You can also style the link purely with css.
The html code :
<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"></a>
The css code :
.facebook-share-button {
background-image: url("/img/facebook-share-button.png");
display: inline-block;
height: 32px;
width: 32px;
}
.facebook-share-button:active,
.facebook-share-button:focus,
.facebook-share-button:hover {
background-image: url("/img/facebook-share-button-hover.png");
}
You can simply do something like...
...
<head>
...
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id', // you need to create an facebook app
autoLogAppEvents : true,
xfbml : true,
version : 'v3.3'
});
};
</script>
<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>
</head>
<body>
...
<button id="share-btn"></button>
<!-- load jquery -->
<script>
$('#share-btn').on('click', function () {
FB.ui({
method: 'share',
href: location.href, // Current url
}, function (response) { });
});
</script>
</body>
Include the facebook button on the page which you want to share
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://trial.com/news.php?newsid=<?php echo $content; ?>">
<img src="http://trial/new_img/facebook_link.png" style=" border: 1px solid #d9d9d9; box-shadow: 0 4px 7px 0 #a5a5a5; padding: 5px;" title="facebook_link" alt="facebook_link" />
</a>
When I like the page from my site, the link is from index...I need that this link be the link of the correct page...I'm trying to take the url address( have the index of my site..then I click in a image..and open another link with infos from my photo. There has a like button and when I click , this like the link of the first page of my site , don't the current page)
I'm trying to follow this tutorial: http://support.addthis.com/customer/portal/articles/381249-adding-parameters-to-urls#.UW1-Kit8KPV
here is the code that I have tried:
<style type="text/css">
.float-all {
float: left;
width: 82px;
height: 30px;
overflow: hidden;
margin: 2px;
padding: 4px 2px;
}
.post-btn-share {
width: 100%;
overflow: auto;
}
</style>
<!-- AddThis Button BEGIN -->
<div class="post-btn-share">
<div class="addthis_toolbox addthis_default_style">
<div class="float-all">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
</div>
<div class="float-all">
<a class="addthis_button_tweet"></a>
</div>
<div class="float-all">
<a class="addthis_button_google_plusone" g:plusone:size="medium"></a>
</div>
</div>
</div>
<script type="text/javascript">
var addthis_share = {
url_transforms : {
add: {
img: '<?php echo $_GET['img']; ?>',
user: '<?php echo $_GET['user']; ?>'
}
}
}
</script>
<script type="text/javascript">var addthis_config = {"data_track_addressbar":true};</script>
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-51473a5c09315ac4"></script>
<!-- AddThis Button END -->
Going through the AddThis support site I found this article regarding URL & Title:
http://support.addthis.com/customer/portal/articles/381242-url-title#.UW26obVg8y4.
Note: Some services, most notably Facebook and LinkedIn, do not use
parameters we send to them. Rather, they use meta tags to determine
the URL, title, and description to share. See this blog post for more
information. See this blog post for more information.