Using Facebooks Developers API to access user's friend information - php

I'm currently working on a website that allows a user to login though Facebook and from that get all of their information to be used on my site.
e.g If they are single or are they interested in women men or both.
I have been looking around on the Facebook Developers side of there site and there is some sample code on there for getting information about what films they like, so I was just wondering if it is possible to change and adapt this to what I need.
Here's some of the code I have found from this page and where it explains it:
http://developers.facebook.com/blog/post/481
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#
appId=YOUR_APP_ID&xfbml=1"></script>
<fb:login-button show-faces="true" width="200" max-rows="1"
perms="user_likes, friends_likes"></fb:login-button>
FB.api('/me/friends', function(response) { });
FB.api(‘/USER_ID/movies’, function(response) { });
FB.api('/'+movieListSorted[i].id, function(response) {
var newDiv = document.createElement("DIV");
newDiv.innerHTML = "<img src='"+response.picture+"'></img><br/>";
if( response.link) {
newDiv.innerHTML+="<a href='"+response.link+"'>"+response.link
+"</a><br/>";
newDiv.innerHTML+='<iframe src="http://www.facebook.com'
+ '/plugins/like.php?'
+ 'href='+response.link+'&layout=standard&'
+ 'show_faces=true&'
+ 'width=450&action=like&colorscheme=light'
+ '&height=80"'
+ 'scrolling="no" frameborder="0" style="border:none;'
+ 'overflow:hidden;'
+ 'width:450px; height:80px;" allowTransparency="true">
+ '</iframe><br/>';
}
document.getElementById(response.id).appendChild(newDiv);
});
<html>
<head>
<title>Test Page</title>
<script>
var movieList = new Array();
var movieListSorted = new Array();
var friendCount = 0;
function showMovies() {
alert(movieList.length);
}
function compareMovies(movieA, movieB) {
if (movieA.name === movieB.name) return 0;
if (movieA.name > movieB.name) return 1;
return -1;
}
function popularMovies(movieA, movieB) {
return movieB.mCount - movieA.mCount;
}
function data_fetch_postproc() {
document.getElementById('test').innerHTML
= "Generating recommendations ... ";
movieList.sort(compareMovies);
// Now we have sorted list, dedupe and count
mCtr = 0;
for (i = 0; i < movieList.length; i++)
{
var count = 0;
movieListSorted[mCtr] = movieList[i];
for ( j = i; j < movieList.length; j++)
{
if ( movieList[i].name === movieList[j].name ) {
count++;
} else {
break;
}
}
i = i+count-1;
movieListSorted[mCtr++].mCount = count;
}
var maxResults = 100;
if( movieListSorted.length < 100) {
maxResults = movieListSorted.length;
}
movieListSorted.sort(popularMovies);
document.getElementById('test').innerHTML = "";
for( i=0; i<maxResults; i++) {
var newDiv = document.createElement("DIV");
newDiv.id = movieListSorted[i].id;
newDiv.innerHTML = movieListSorted[i].name + ' : Likes - '
+ movieListSorted[i].mCount;
document.getElementById("movies").appendChild(newDiv);
FB.api('/'+movieListSorted[i].id, function(response) {
var newDiv = document.createElement("DIV");
newDiv.innerHTML = "<img src='"+response.picture+"'>"
+ "</img><br/>";
if( response.link) {
newDiv.innerHTML+= "<a href='"+response.link+"'>"
+response.link+"</a><br/>";
newDiv.innerHTML+= '<iframe src='
+ '"http://www.facebook.com/plugins/like.php?'
+ 'href='+response.link+'&layout=standard'
+ '&show_faces=true&'
+ 'width=450&action=like&'
+ 'colorscheme=light&height=80"'
+ 'scrolling="no" frameborder="0" style="'
+ 'border:none; overflow:hidden;'
+ 'width:450px; height:80px;"'
+ 'allowTransparency="true"></iframe><br/>';
}
document.getElementById(response.id).appendChild(newDiv);
});
}
}
function get_friend_likes() {
document.getElementById('test').innerHTML = "Requesting "
+ "data from Facebook ... ";
FB.api('/me/friends', function(response) {
friendCount = response.data.length;
for( i=0; i<response.data.length; i++) {
friendId = response.data[i].id;
FB.api('/'+friendId+'/movies', function(response) {
movieList = movieList.concat(response.data);
friendCount--;
document.getElementById('test').innerHTML = friendCount
+ " friends to go ... ";
if(friendCount === 0) { data_fetch_postproc(); };
});
}
});
}
</script>
</head>
<body>
<div id="fb-root"></div>
<div id="login"></div>
<div id="test"></div>
<div id="movies"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR_APP_ID',
status : true, // check login status
cookie : true, // enable cookies
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.sessionChange', function(response) {
window.location.reload();
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
get_friend_likes();
document.getElementById('login').innerHTML
='Logout<br/>';
} else {
document.getElementById('login').innerHTML
='<fb:login-button show-faces="true" width="200"'
+ ' max-rows="1" perms="user_likes, friends_likes">'
+ '</fb:login-button>';
FB.XFBML.parse();
}
});
</script>
</body>
</html>

Have you checked out the Graph API:
Facebook Graph API
You also have to make sure you have the proper permissions:
Facebook API Permissions

I'd recommend using the PHP SDK to get this information, especially if you're a beginner. You can use their functions then.
You can find the source code for this (and some documentation included) at the following URL:
https://developers.facebook.com/docs/reference/php/
First of all, in order to get anything from the Graph API, you will need to gain the authentication of the user for your application, this is documented here:
https://developers.facebook.com/docs/authentication/
Then, you can get the information that you need about the current user, using an API call. This is documented here:
http://developers.facebook.com/docs/reference/php/facebook-api/
The code of note here is below, I have edited this to provide the currently logged in user's 'interested_in' field as documented here:
try {
$user_profile = $facebook->api('/me?fields=interested_in','GET');
echo "Interested in: " . $user_profile['interested_in'];
} catch(FacebookApiException $e) {
// Failed API call
error_log($e->getType());
error_log($e->getMessage());
}

Related

Jquery Scroll Loading All The Rows At Once And Should Only Load 5 At A Time

I am using the following script to load more, 5 rows at a time from the database, on scroll. All the rows are loading at once on scroll after the initial loads correctly. In realtime, the first 5 load. Then on scroll the last 14 load at once. Like it rushes to the end instead of incrementally loading 5 at a time. I use the same code for a load more button and it works fine. Same PHP file for both. No issue with that. Can anyone see why all the rows are being loaded on scroll instead of 5 at a time.
<script>
//SET NUMBER OF ROWS TO DISPLAY AT A TIME
rowsPerPage = 5;
$(document).ready(function() {
// GETTING DATA FROM FUNCTION BELOW
getData();
window.onscroll = function() {
if ($(window).scrollTop() >= $('#load-container').offset().top + $('#load-container').outerHeight() - window.innerHeight) {
$('#load-more').html('Loading...');
var rowID = Number($("#row-id").val());
var allCount = Number($("#count").val());
rowID += rowsPerPage;
if (rowID <= allCount) {
$("#row-id").val(rowID);
getData();
} else {
$('#load-more').html('End Of Data');
//$('#load-more').html('');
}
}
}
/* REQUEST DATA */
function getData() {
var rowID = $("#row-id").val();
var allCount = $("#count").val();
$('#load-more').html('Loading...');
$.ajax({
url: 'promotions/newest-load-scroll-data-invalid.php',
type: 'post',
data: {
rowID: rowID,
rowsPerPage: rowsPerPage
},
dataType: 'json',
success: function(response) {
setTimeout(function() {
loadData(response)
}, 1000);
},
});
}
/* LOAD DATA TO PAGE */
function loadData(data) {
var dataCount = data.length;
for (var i = 0; i < dataCount; i++) {
if (i == 0) {
var allCount = data[i]['allcount'];
$("#count").val(allCount);
} else {
var promoID = data[i]['promoid'];
var promoNameNewest = data[i]['promoname'];
var promoNameNewestVideo = data[i]['promoname'];
var promoRefNum = data[i]['promorefnum'];
var promoType = data[i]['promotype'];
var theBanner = data[i]['thebanner'];
var email = data[i]['email'];
var customerType = data[i]['customerType'];
if (email == "") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="visitor-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="visitor-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
if (customerType == "p") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="advertiser-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="advertiser-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
}
$('#load-more').html('Loading...');
}
}
});
</script>
I was able to utilize flags to make it work right with a couple other small changes. Appreciate the input, Taplar.

using ajax to move javascript variable value to php variable?

I'm very new to coding and am creating an online system. Part of the system I have included Google Distance Matrix API which is JavaScript, whereas most of my other code is HTML or PHP. Unfortunately, I need the distance (which is calculated in JavaScript) to be in my PHP code so I can play about with it. I read I could use AJAX? I'm not terribly sure about what I'm doing but I had a go.
Before the page that includes the Google Map, there is a form. This means I have to use SESSION variables to move the data from the page before the Google page, to two pages after the Google page.. this is also where my Google script gets it's two locations to find the distance between. Which all works fine, I think.
PHP on Google page:
$date = $_POST['date'];
$time = $_POST['time'];
$length = $_POST['length'];
$numberofpeople = $_POST['numberofpeople'];
$useofbus = $_POST['useofbus'];
session_start();
$_SESSION['time'] = $time;
$_SESSION['date'] = $date;
$_SESSION['length'] = $length;
$_SESSION['numberofpeople'] = $numberofpeople;
$_SESSION['pickuplocation'] = $pickuplocation;
$_SESSION['destination'] = $destination;
$_SESSION['useofbus'] = $useofbus;
$pickuplocation = $_POST['pickuplocation'];
$destination = $_POST['destination'];
HTML on Google page:
</head>
<body onload="initialize()">
<div id="inputs">
<pre class="prettyprint">
</pre>
<form name="google" action="thirdform.php">
<table summary="google">
<tr>
<td> </td>
<td><input name="Continue" value="Continue" type="submit" ></td>
<td> </td>
</tr>
</table>
</form>
</div>
<div id="outputDiv"></div>
<div id="map"></div>
</body>
</html>
I won't post the JavaScript of the Google Matrix other than the AJAX:
var distance = results[j].distance.text;
$.get("thirdform.php", {miles:distance} );
I'm not sure if the code above is correct, I'm guessing I'm going wrong somewhere, probably here.
On the next page, (thirdform.php) PHP:
session_start();
$time = $_SESSION['time'];
$date = $_SESSION['date'];
$length = $_SESSION['length'];
$numberofpeople = $_SESSION['numberofpeople'];
$pickuplocation = $_SESSION['pickuplocation'];
$destination = $_SESSION['destination'];
$useofbus = $_SESSION['useofbus'];
var_dump($_SESSION);
echo "</br>";
$distance = $_GET['miles'];
echo "DISTANCE: " . $distance . "</br>";
I'm not able to get anything in the PHP variable $distance - it's empty. Am I coding incorrectly? I followed an example on-line from this website somewhere which claimed to work. I've read several articles and searched on Google and on this website but there doesn't seem to be a clear answer anywhere that isn't too complicated and relates to what I'm trying to do. I've read plenty of examples but they're all far too complicated for me to use and change to put into my code. There was some code I read where the page was sent straight to next page however I need to show the Google Map on my page and therefore need to use the button to move to the next page.
Could anyone give me a nudge in the right direction? Thanks.
JS:
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin = '<?php echo $pickuplocation; ?>';
var destination = '<?php echo $destination; ?>';
var destinationIcon = 'https://chart.googleapis.com/chart? chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
geocoder = new google.maps.Geocoder();
calculateDistances()
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
<script type="text/javascript">
var distance = results[j].distance.text;
$('.button-class').click(function() { $.get("thirdform.php", {miles:distance}, function (data){alert(data)} ); });
</script>
Since you are overriding the form action with the $.get, try removing the form and using a <button> instead of an <input> button.
Then have your ajax request run on that <button>.
Edit:
It's also worth noting that you should probably just send data from the php file. You can then do any other manipulation("DISTANCE: ", "<br />") in the html/js.

getting multiple post id wordpress

I am making a voting system for my theme
It is working fine in single.php
But when i keep it in index.php it only considers the id of first post and rest don't work
I think its not dealing with multiple post id
Here is the full code
Setting a cookie, calling Ajax action with jQuery
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$("#vote").not(".disabled").click(function() {
var el = $(this);
el.html('<span id="loader"></span>');
var nonce = $("input#voting_nonce").val();
var data = {
action: 'add_votes_options',
nonce: nonce,
postid: '<?php echo $post->ID; ?>',
ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'
};
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data,
function(response){
if(response!="-1") {
el.html("VOTED").unbind("click");
if(response=="null") {
alert("A vote has already been registered to this IP address.");
} else {
$("#votecounter").html(response);
alert("Thanks for your vote.");
}
var cookie = getCookie("better_votes");
if(!cookie) {
var newcookie = "<?php echo $post->ID; ?>";
} else {
var newcookie = cookie + ",<?php echo $post->ID; ?>";
}
setCookie("better_votes", newcookie, 365);
} else {
alert("There was a problem registering your vote. Please try again later.");
}
});
return false;
});
})(jQuery);
/* ]]> */
</script>
This is what I put in my functions.php to register actions
add_action("wp_ajax_add_votes_options", "add_votes_options");
add_action("wp_ajax_nopriv_add_votes_options", "add_votes_options");
function add_votes_options() {
if (!wp_verify_nonce($_POST['nonce'], 'voting_nonce'))
return;
$postid = $_POST['postid'];
$ip = $_POST['ip'];
$voter_ips = get_post_meta($postid, "voter_ips", true);
if(!empty($voter_ips) && in_array($ip, $voter_ips)) {
echo "null";
die(0);
} else {
$voter_ips[] = $ip;
update_post_meta($postid, "voter_ips", $voter_ips);
}
$current_votes = get_post_meta($postid, "votes", true);
$new_votes = intval($current_votes) + 1;
update_post_meta($postid, "votes", $new_votes);
$return = $new_votes>1 ? $new_votes." votes" : $new_votes." vote";
echo $return;
die(0);
}
this is how I call my vote button and count button
<?php
// This will display "0 votes" and increase as votes are added
$votes = get_post_meta($post->ID, "votes", true);
$votes = !empty($votes) ? $votes : "0";
if($votes == 1) $plural = ""; else $plural = "s";
echo '<div id="votecounter">'.$votes.' vote'.$plural.'</div>';
?>
<?php
// This will display the vote button and disable it if a cookie has already
// been set. We also add the security nonce here.
$hasvoted = $_COOKIE['better_votes'];
$hasvoted = explode(",", $hasvoted);
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = ' class="disabled"';
} else {
$vtext = "VOTE";
$class = "";
}
?>
<a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo $vtext; ?></a>
<?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce', 'voting_nonce'); ?>
As for a beginning, you shouldn't have the same id for your button over and over again, so change this:
<a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo $vtext; ?></a>
To this:
<?php
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = ' disabled';
} else {
$vtext = "VOTE";
$class = "";
}
<?php echo $vtext; ?>
This will result in id attribute of each vote button in the form of "vote-{post id}". And since I guess you still want to address all of your buttons in some way, you can now use the .vote-btn selector.
The problem with your JavaScript is that you pass the ID of the post to the script directly. This is fine, when you have only one post on the page, but when you have multiple posts, you have to either print your code multiple times, or get the post ID dynamically.
I prefer the second option, here's how your JS code should change in order to get that working:
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$(".vote-btn").not(".disabled").click(function() {
var el = $(this),
nonce = $("input#voting_nonce", el.parent()).val(),
id = el.attr('id').replace(/vote-/, ''); // get the Post ID
el.html('<span id="loader"></span>');
var data = {
action: 'add_votes_options',
nonce: nonce,
postid: id,
ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'
};
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data,
function(response){
if(response!="-1") {
el.html("VOTED").unbind("click");
if(response=="null") {
alert("A vote has already been registered to this IP address.");
} else {
$("#votecounter").html(response);
alert("Thanks for your vote.");
}
var cookie = getCookie("better_votes");
if(!cookie) {
var newcookie = id;
} else {
var newcookie = cookie + "," + id;
}
setCookie("better_votes", newcookie, 365);
} else {
alert("There was a problem registering your vote. Please try again later.");
}
});
return false;
});
})(jQuery);
/* ]]> */
</script>
So, in the above code, we get the ID of the post that the user is voting from, by replacing "vote-" with an empty string(so only the ID remains). Note also the following line:
nonce = $("input#voting_nonce", el.parent()).val(),
In this line, I assume that the nonce input as well as the button have the same parent(although you should be able to use the same nonce for all posts). You can also take your nonce one step further, by changing the code that generates it to:
<?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce-' . $post->ID, 'voting_nonce'); ?>
And change your add_votes_options function to:
$postid = $_POST['postid'];
if ( ! wp_verify_nonce( $_POST['nonce'], 'voting_nonce-' . $postid ) )
return;
This will bind each nonce to the ID of the post, that the nonce is for.
I think that's pretty much your problem. Please try my code and tell me if there are problems with it(if it's a JS error, please add message from the error console in FireBug, or WebKit's inspector).
PP: Just saw this:
Looking for an answer drawing from credible and/or official sources.
My answer was backed-up by my experience with WordPress and jQuery - and I earn my living by working mainly with WordPress(less jQuery, but I use it relatively often as well). Hope this will be enough :)

How to fix a not defined javascript error?

I am fairly new to Javascript and what I am trying to do is have a cookie set as soon as I click on a link. When I return back to the previous page from the link, I want the page to auto refresh and notify the user by color to show what link they just clicked. I used this example to guide me http://webdesign.about.com/od/cookies/a/aa083198.htm. But I am still not getting it.
The code below is what I have. The problem is that as soon as I click on the link firebug brings up the error "getLink not defined". Also through web developer on Firefox, it seems that my cookie is not actually being set even though I am calling it from the Html.I am also showing gave the most important part in my Html that calls the function.
The videoId i have in setCookie is a php variable that is defined somewhere else in my code. I would really appreciate it if someone can point me in the right direction. Thanks!
<head>
<script language="text/javascript">
var cookie_name = "watched";
function setCookie(cookie_name,cookie_value)
{
if (document.cookie!="") {
index = document.cookie.indexOf(cookie_name);
} else {
index = -1;
}
if (index == -1) {
var finish = 7200;
var cookie_value = videoId + "; expires=" + finish;
document.cookie=cookie_name + "=" + cookie_value;
}
}
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks;
}
else{
//alert("No color");
}
}
return colorLinks;
}
function colorLinks()
{
$('#' + videoId).css('background-color: pink');
}
</script>
</head>
<body onLoad=window.refresh>
<div id="page">
echo '<a href="' . $link . '" onclick="setCookie(); return true;">' . $this->Links
This does not make sense:
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks; // you mean colorLinks(); ???
}
else {
//alert("No color");
}
}
// why return a function that sets color instead of just calling it?
return colorLinks;
}
and there is luckily nothing called window.refresh (unless you have created it yourself) or you would loop forever
In the code i don't see where videoId is given a value
You don't call the function setCookie(cookie_name,cookie_value); to set the cookie.
Please read about cookies: http://www.quirksmode.org/js/cookies.html
<script type = "text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script>

array from php to JavaScript

i am trying to transfer a array list from php to javascript with json, but it does not work.
JS:
$.ajax({
url: 'getProfilePhotos.php',
type: 'post', // post or get method
data: {}, // if you need to pass post/get parameterds you can encode them here in JSON format
dataType: 'json', // the data type you want returned... we will use json
success: function(responseData) {
var arrayList[0] = new Array();
var lung = arrayList.length;
for(var i = 0; i<lung; i++)
//arrayList[i] = responseData.i;
console.log(responseData.i);
}});
PHP:
<p> <?php
$array = array();
$nr = count($friends['data']);
for($i = 0; $i < $nr; $i++){
$array = 'link'=>array("http://graph.facebook.com/".$friends['data'][$i]['id']."/picture");
?>
<img src="http://graph.facebook.com/<?php echo $friends['data'][$i]['id'] ?>/picture" />
<?php
}
header('Content-type: application/json');
echo json_encode($array);
?></p>
Update for Christopher McCann
i have got a error in console. this is the error.
[02:46:21.281] missing } after property list # http://romanager.ro/api/examples/script.js:3
line 3 in script.js is
type: 'post', // post or get method
In fact i want to get from facebook profile photos. with php script i managed to get photos, but i can transfer ids from php to javascript. if you need i will try to write entire php script and javascript files.
Update
still have problems with these scripts. in php script i do and authentification of user on facebook, because i need for user ID from facebook to get ids of his friends. to make login i need to create html in php script. well i will post the code of my scripts and i hope you will help me.
PHP script:
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '137061043024243',
'secret' => '619c4dc94343584eb7792ae9933978c9',
'cookie' => true,
));
// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk</title>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<!--
We use the JS SDK to provide a richer user experience. For more info,
look here: http://github.com/facebook/connect-js
-->
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<?php if ($me): ?>
<a href="<?php echo $logoutUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
</a>
<?php else: ?>
<div>
Using JavaScript & XFBML: <fb:login-button></fb:login-button>
</div>
<div>
Without using JavaScript & XFBML:
<a href="<?php echo $loginUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
</a>
</div>
<?php endif ?>
<?php $array = array();
$nr = count($friends['data']);
echo $nr;
for($i = 0; $i < $nr; $i++) {
$array[$i] = "http://graph.facebook.com/".$friends['data'][$i]['id']."/picture";
}
header('Content-type: application/json');
echo json_encode($array);
?>
</body>
</html>
JAVASCRIPT
$.post("getProfilePhotos.php", function(data) { alert(data); console.log(data);/*DO WHAT YOU WANT WITH DATA HERE*/}, "json");
window.onload = init;
function init() {
if (window.Event) {
document.addEventListener("mousemove", getCursorXY("mousemove"), false);
var cursorXX = 0;
var cursorYY = 0;
var cursorX = document.getElementById("cursorX");
var cursorY = document.getElementById("cursorY");
cursorX.innerHTML = cursorXX;
cursorY.innerHTML = cursorYY;
}
//initializare canvas1
canvas = document.getElementById('game');
//coordonatele unde se afla mouseul
canvas.onmousemove = getCursorXY;
//initializare canvas2
canvas2 = document.getElementById('teroristi');
//coordonatele unde se afla mouseul
canvas2.onmousemove = getCursorXY;
//lista de inamici
lista = new Array();
initial();
for(var j = 0; j < 20; j++)
for(var k = 0; k < 2;k++)
console.log(matx[j][k]);// = -1000;
scor = 0;
viata = 5;
//creerea contextului de desenare 2D
ctx2 = canvas2.getContext("2d");
ctx = canvas.getContext("2d");
//creerea unui obiect imagine
img = new Image();
img.src = 'glont.png';
imgTerorist = new Image();
imgTerorist.src = 'terorist.jpg';
ctx.beginPath();
ctx.stroke();
imgviata = new Image();
imgviata.src = 'vieti.png';
//score();
viataF();
}
//initializeaza matricea de aparitii
function initial(){
matx = new Array(24);
for (var m = 0; m <24; m++)
matx[m] = new Array(3);
for(var m = 0; m < 24; m++)
matx[m][2] = 0;
matx[0][0] = 20;
matx[0][1] = 20;
for(var m = 1; m < 6; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
matx[6][0] = matx[0][0];
matx[6][1] = matx[0][1] + 120;
for(var m = 7; m < 12; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
matx[12][0] = matx[0][0];
matx[12][1] = matx[0][1] + 240;
for(var m = 13; m < 18; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
matx[18][0] = matx[0][0];
matx[18][1] = matx[0][1] + 360;
for(var m = 19; m < 24; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
}
function getCursorXY(e) {
//se ia pozitia de pe axa x al cursorului
cursorXX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
//se ia pozitia de pe axa y al cursorului
cursorYY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
//
var cursorX = document.getElementById("cursorX");
var cursorY = document.getElementById("cursorY");
cursorX.innerHTML = cursorXX;
cursorY.innerHTML = cursorYY;
}
function Nr(){
return Math.floor(Math.random()*24);
}
//stergerea inamicului
function sterge(x){
//setTimeout("genereaza(flag)",3000);
var img = ctx.createImageData(60, 100);
for (var i = img.data.length; --i >= 0; )
img.data[i] = 0;
ctx.putImageData(img, matx[x][0], matx[x][1]);
matx[x][2] = 0;
}
//genereaza inamici
function genereaza(flag){
if(flag == 1){
setTimeout("genereaza(flag)", 2000);
var x = Nr();
terorist(x);
if(lista.length > 3){
viata = viata - 1;
sterge(lista[0]);
lista.splice(0, 1);
viataF();
}
}
}
//creeaza un inamic
function terorist(x){
console.log("X primit = " + x + "valoarea flagului = " + matx[x][2]);
//sterge(x);
if(matx[x][2] == 0){
ctx.drawImage(imgTerorist,matx[x][0],matx[x][1]);
matx[x][2] = 1;
lista.push(x);
}
else if(matx[x][2] == 1){
var q = Nr();
console.log("in recursie: " + q);
terorist(q);
}
}
function viataF(){
var remove = ctx2.createImageData(20,20);
for (var i = remove.data.length; --i >= 0; )
remove.data[i] = 0;
ctx2.putImageData(remove, 10, (10+(viata*20)));
console.log(viata);
for(var m = 0; m < viata; m++)
ctx2.drawImage(imgviata,10,(10+(m*20)));
}
function impuscat(){
var shootX = cursorXX;
var shootY = cursorYY;
var tm = 0;
console.log("ShootX = " + shootX + " ShootY = " + shootY);
for(var m = 0, tm = lista.length; m < tm; m++){
if(shootX >= matx[lista[m]][0] && shootX <= matx[lista[m]][0] + 60 && shootY >= matx[lista[m]][1] && shootY <= matx[lista[m]][1] + 100){
sterge(lista[m]);
lista.splice(m, 1);
scor = scor + 10;
console.log("IMPUSCAT");
}
}
}
function glont(x, y){
ctx.beginPath();
ctx.stroke();
ctx.drawImage(img,x-40,y-40);
impuscat();
}
function mouse(){
impuscat();
/*console.log('Maus apasat');
console.log(cursorXX);
console.log(cursorYY);*/
//glont(cursorXX, cursorYY);
//console.log("Dupa glont()");
}
function start(){
viataF();
flag = 1;
genereaza(flag);
setTimeout("stop()", 10000);
}
function stop(){
ctx2.fillStyle = '#000000';
ctx2.strokeStyle = '#FFFFFF';
ctx2.font = 'bold 30px sans-serif';
ctx2.fillText ('TIMPUL A EXPIRAT!', 100, 200);
ctx2.fillText('Scorul tau este: ' + scor, 100, 235);
console.log("TIMPUL A EXPIRAT");
flag = 0;
genereaza(flag);
}
function score(){
ctx2.fillStyle = '#000000';
ctx2.strokeStyle = '#FFFFFF';
ctx2.font = 'bold 15px sans-serif';
ctx2.fillText('Scorul tau este: ', 350, 20);
}
Your PHP section is wrong as you are still trying to generate HTML, rather than just JSON.
Also the array handling within the loop is incorrect.
Try changing the PHP code to:
<?php
$friendData = array();
foreach ($friends['data'] as $cFriend) {
$friendData[$cFriend['id']] = "http://graph.facebook.com/" . $cFriend['id'] . "/picture";
}
header('Content-Type: application/json');
echo json_encode($friendData);
exit;
Header will not work in this case as you cannot output any content (including whitespace) to the browser before you call header(). In your for loop you output HTML to the browser which will cause an error.
As Orbling said you are also not correctly adding the element to the array. I am just assuming this is what you want but the loop you want is:
for($i = 0; $i < $nr; $i++) {
$array[] = "http://graph.facebook.com/".$friends['data'][$i]['id']."/picture";
}
I am confused by what you are trying to achieve with your javascript. I would use the following code instead to simplify:
$.post("getProfilePhotos.php", function(data) { alert(data); //DO WHAT YOU WANT WITH DATA HERE }, "json");
I would run that code first to check you get the JSON back and then play about with the callback function to do what you want with the returned json.

Categories