App works only for but not for other users - authentication

I am editing the default app provided by the heroku. This works with my login. But other users doesn't see app working. My app requires permission - user_relationships, friends_relationships.
When I debug the access_token seen by the user, it correctly specifies the above permissions.
Somebody can please point me what is the issue?? Thanks in advance.
<?php
// Provides access to app specific values such as your app id and app secret.
// Defined in 'AppInfo.php'
require_once('AppInfo.php');
// Enforce https on production
if (substr(AppInfo::getUrl(), 0, 8) != 'https://' && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
header('Location: https://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit();
}
// This provides access to helper functions defined in 'utils.php'
require_once('utils.php');
/****************************************************************************
*
* The content below provides examples of how to fetch Facebook data using the
* Graph API and FQL. It uses the helper functions defined in 'utils.php' to
* do so. You should change this section so that it prepares all of the
* information that you want to display to the user.
*
****************************************************************************/
require_once('sdk/src/facebook.php');
// Instantiating Facebook object to access SDK
$facebook = new Facebook(array(
'appId' => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
));
// Returns facebook user id of the current user
$user_id = $facebook->getUser();
if ($user_id) {
try {
// Fetch the viewer's basic information
$basic = $facebook->api('/me');
} catch (FacebookApiException $e) {
// If the call fails we check if we still have a user. The user will be
// cleared if the error is because of an invalid accesstoken
if (!$facebook->getUser()) {
header('Location: '. AppInfo::getUrl($_SERVER['REQUEST_URI']));
exit();
}
}
$access_token = $facebook->getAccessToken();
echo $access_token;
// Here is an example of a FQL call that fetches all of your friends that are
// using this app
$app_using_friends = $facebook->api(array(
'method' => 'fql.query',
'query' => 'SELECT uid, name, relationship_status FROM user WHERE uid IN(SELECT uid2 FROM friend WHERE uid1 = me())'
));
}
// Fetch the basic info of the app that they are using
$app_info = $facebook->api('/'. AppInfo::appID());
$app_name = idx($app_info, 'name', '');
?>
<!DOCTYPE html>
<html xmlns:fb="http://ogp.me/ns/fb#" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes" />
<title><?php echo he($app_name); ?></title>
<link rel="stylesheet" href="stylesheets/screen.css" media="Screen" type="text/css" />
<link rel="stylesheet" href="stylesheets/mobile.css" media="handheld, only screen and (max-width: 480px), only screen and (max-device-width: 480px)" type="text/css" />
<!--[if IEMobile]>
<link rel="stylesheet" href="mobile.css" media="screen" type="text/css" />
<![endif]-->
<!-- These are Open Graph tags. They add meta data to your -->
<!-- site that facebook uses when your content is shared -->
<!-- over facebook. You should fill these tags in with -->
<!-- your data. To learn more about Open Graph, visit -->
<!-- 'https://developers.facebook.com/docs/opengraph/' -->
<meta property="og:title" content="<?php echo he($app_name); ?>" />
<meta property="og:type" content="website" />
<meta property="og:url" content="<?php echo AppInfo::getUrl(); ?>" />
<meta property="og:image" content="<?php echo AppInfo::getUrl('/logo.png'); ?>" />
<meta property="og:site_name" content="<?php echo he($app_name); ?>" />
<meta property="og:description" content="My first app" />
<meta property="fb:app_id" content="<?php echo AppInfo::appID(); ?>" />
<script type="text/javascript" src="/javascript/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function logResponse(response) {
if (console && console.log) {
console.log('The response was', response);
}
}
$(function(){
// Set up so we handle click on the buttons
$('#postToWall').click(function() {
FB.ui(
{
method : 'feed',
link : $(this).attr('data-url')
},
function (response) {
// If response is null the user canceled the dialog
if (response != null) {
logResponse(response);
}
}
);
});
$('#sendToFriends').click(function() {
FB.ui(
{
method : 'send',
link : $(this).attr('data-url')
},
function (response) {
// If response is null the user canceled the dialog
if (response != null) {
logResponse(response);
}
}
);
});
$('#sendRequest').click(function() {
FB.ui(
{
method : 'apprequests',
message : $(this).attr('data-message')
},
function (response) {
// If response is null the user canceled the dialog
if (response != null) {
logResponse(response);
}
}
);
});
});
</script>
<!--[if IE]>
<script type="text/javascript">
var tags = ['header', 'section'];
while(tags.length)
document.createElement(tags.pop());
</script>
<![endif]-->
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo AppInfo::appID(); ?>', // App ID
channelUrl : '//<?php echo $_SERVER["HTTP_HOST"]; ?>/channel.html', // Channel File
//oauth : true,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
//FB.login({
// scope : 'user_relationships,friends_relationships'
// });
// Listen to the auth.login which will be called when the user logs in
// using the Login button
FB.Event.subscribe('auth.login', function(response) {
// We want to reload the page now so PHP can read the cookie that the
// Javascript SDK sat. But we don't want to use
// window.location.reload() because if this is in a canvas there was a
// post made to this page and a reload will trigger a message to the
// user asking if they want to send data again.
window.location = window.location;
});
FB.Canvas.setAutoGrow();
};
// Load the SDK Asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<header class="clearfix">
<?php if (isset($basic)) { ?>
<p id="picture" style="background-image: url(https://graph.facebook.com/<?php echo he($user_id); ?>/picture?type=normal)"></p>
<div>
<h1>Welcome, <strong><?php echo he(idx($basic, 'name')); ?></strong></h1>
<p class="tagline">
This is my app. My First Facebook app.
<?php echo he($app_name); ?>
</p>
<div id="share-app">
</div>
<?php } else { ?>
<div>
<h1>Welcome</h1>
<div class="fb-login-button" data-scope="user_likes,user_photos,user_relationships,friends_relationships"></div>
</div>
<?php } ?>
</header>
<?php
if ($user_id) {
?>
var $shaheeds = 0;
var $aazaads = 0;
var $confused = 0;
var $in_trap = 0;
var $total = 0;
<section id="samples" class="clearfix">
<h1>Examples of the Facebook Graph API</h1>
<div class="list">
<h3>Shaheed Friends</h3>
<ul class="shaheed">
<?php
foreach ($app_using_friends as $friend) {
// Extract the pieces of info we need from the requests above
$id = idx($friend, 'uid');
$name = idx($friend, 'name');
$r_status = idx($friend, 'relationship_status');
if($r_status == "Married"){
$shaheeds++;
?>
<li>
<a href="https://www.facebook.com/<?php echo he($id); ?>" target="_top">
<img src="https://graph.facebook.com/<?php echo he($id) ?>/picture?type=square" alt="<?php echo he($id); ?>">
<?php echo he($name); ?>
</a>
</li>
<?php
}
}
?>
</ul>
</div>
<div class="list inline">
<h3>Recent photos</h3>
<ul class="photos">
<?php
$i = 0;
foreach ($photos as $photo) {
// Extract the pieces of info we need from the requests above
$id = idx($photo, 'id');
$picture = idx($photo, 'picture');
$link = idx($photo, 'link');
$class = ($i++ % 4 === 0) ? 'first-column' : '';
?>
<li style="background-image: url(<?php echo he($picture); ?>);" class="<?php echo $class; ?>">
</li>
<?php
}
?>
</ul>
</div>
<div class="list">
<h3>Friends In Trap</h3>
<ul class="in-trap">
<?php
foreach ($app_using_friends as $friend) {
// Extract the pieces of info we need from the requests above
$id = idx($friend, 'uid');
$name = idx($friend, 'name');
$r_status = idx($friend, 'relationship_status');
if($r_status == "Engaged" || $r_status == "In a relationship"){
// This display's the object that the user liked as a link to
// that object's page.
$in_trap++;
?>
<li>
<a href="https://www.facebook.com/<?php echo he($id); ?>" target="_top">
<img src="https://graph.facebook.com/<?php echo he($id) ?>/picture?type=square" alt="<?php echo he($name); ?>">
<?php echo he($name); ?>
</a>
</li>
<?php
}
}
?>
</ul>
</div>
<div class="list">
<h3>Azaad Friends</h3>
<ul class="friends">
<?php
foreach ($app_using_friends as $auf) {
// Extract the pieces of info we need from the requests above
$id = idx($auf, 'uid');
$name = idx($auf, 'name');
$r_status = idx($auf, 'relationship_status');
if($r_status == "Single"){
$aazaads++;
?>
<li>
<a href="https://www.facebook.com/<?php echo he($id); ?>" target="_top">
<img src="https://graph.facebook.com/<?php echo he($id) ?>/picture?type=square" alt="<?php echo he($name); ?>">
<?php echo he($name); ?>
</a>
</li>
<?php
}
$total++;
}
$confused = $total - $aazaads - $shaheeds - $in_trap;
?>
</ul>
</div>
</section>
<section id="graphs" class="clearfix">
<h1>"Graph"</h1>
<img src="http://chart.apis.google.com/chart?cht=p3&chd=t:<?php echo he($shaheeds)?>,<?php echo he($aazaads)?>,<?php echo he($in_trap)?>,<?php echo he($confused)?>&chs=250x100&chl=Shaheed|Aazaad|In Trap|Unknown" />
</section>
<?php
}
?>
</body>
</html>

I am experiencing the same problem. for this one thing is sure we have to disable sandbox mode. for that you must go to facebook developers app. And in that advanced. But i am facing the problem. because to disable sandbox mode we have to provide privacy policy url and secure canvas page url.

Related

How to get a rating value in asp.net mvc4?

I am new asp.net mvc4 with entity frame work, I have designed rating in cshtml file,Pls help me to get a rated value in Controller. Thanks in advance.
This is my cshtml code for rating
{
#{
ViewBag.Title = "Index";
}
<h2>Index rating</h2>
<h2>rating</h2>
#*<form method="post" id="signin" action="#Url.Action("rating", "Rating")">*#
#if (Request.IsAuthenticated)
{
<form method="post" id="signin" action="#Url.Action("rating", "Rating")">
<p>
#DateTime.Now
</p>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="~/Scripts/jquery.js"></script>
<script type="text/javascript" src="~/Scripts/rating.js"></script>
<link rel="stylesheet" type="text/css" href="~/Styles/rating.css" />
<script type="text/javascript">
$(function () {
$('.rating').rating();
$('.ratingEvent').rating({ rateEnd: function (v) { $('#result').text(v); } });
});
</script>
<input type="text" class="ratingEvent rating5" #*id="result"*# value="rating" />
<div><b id="result">5</b> start(s)</div>
<p> </p>
</form>
}
}
This is my Controller code
{
[HttpGet]
public ActionResult rating(int ratedvalue)
{
using (var db = new Project.Models.EntitiesContext())
{
var value= new Project.Models.Tbl_Rating();
var rat = db.Tbl_Rating.FirstOrDefault(u => u.Rating == ratedvalue);
value.Rating = Convert.ToInt32(rat);
return View();
}
}
}
}
try like this
View:
<form method="post" id="signin" action="#Url.Action("rating", "Rating")">
**YOUR CODE**
<input type="text" class="ratingEvent rating5" name="rating" value="rating" /> //Add name attribute
<input type="submit" />
</form>
Controller:
public ActionResult rating(FormCollection form)
{
int ratedvalue=form["rating"]
}

SignalR client script runs only in index page

I'm developing an MVC 4 web application and using signalR library to make a real time notification system.
I have a working script that I use in master page called _Layout.cshtml.
here's the script in _Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="~/signalr/hubs"></script>
</head>
<body >
<header dir="rtl">
<table align="center" cellpadding="0" cellspacing="0" style="width:100%;">
<tr>
<td style="width:30%; height:40px;" valign="top"><img src="~/Images/header_logo3.png" /></td>
<td style="width: 40%; height: 40px; " valign="top"> <a href='#Url.Action("Index","Home")'><img class="header_logo" src='#Url.Content("~/Images/header_logo2.png")' /></a></td>
<td style="width: 30%; height: 40px; " valign="top" ><img src="~/Images/header_logo4.png" /></td>
</tr>
</table>
<h2>Index</h2>
<span id="mySpanTag"></span>
<script type="text/javascript">
//var notificationHub = $.connection.notificationHub;
$(function () {
//Create Hub on Air
var chat = $.connection.notificationHub;
//Messages
$messages = $("#mySpanTag");
//Client Side Method To Access From Server Side Method
chat.client.sendMessage = function (msg) {
$messages.html(msg);
}
$.connection.hub.start(function () {
chat.server.sendMessage("Hello World!");
});
});
</script>
</header>
<div id="wrapper" dir="rtl">
<div id="Smenu" class="visible">
#{Html.RenderAction("Menu", "SettingsMenu", new { id = "nir"});}
</div>
#RenderSection("JavaScript", false)
<section>
#RenderBody()
</section>
</div>
<footer></footer>
</body>
</html>
the Hub class:
using System.Web;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace HaifanetMobile.Hubs
{
public class NotificationHub : Hub
{
public void SendMessage(string msg)
{
Clients.All.sendMessage(msg);
}
}
}
Everything goes ok and I see the massage method called from the hub class in my page, except that
this script is running only on the index.cshtml (startup page) and not in all the web pages in the project or in a specific one of them. e.g not working and the script is the same as you can see:
#model schoolnetMobile.Models.UserModel
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<span id="mySpanTag"></span>
<script type="text/javascript">
//var notificationHub = $.connection.notificationHub;
$(function () {
//Create Hub on Air
var chat = $.connection.notificationHub;
//Messages
$messages = $("#mySpanTag");
//Client Side Method To Access From Server Side Method
chat.client.sendMessage = function (msg) {
$messages.html(msg);
}
$.connection.hub.start(function () {
chat.server.sendMessage("Hello World!");
});
});
</script>
<br /><br />
#if (Request.IsAuthenticated) {
<h4>profile: #Model.UserName</h4>
if (User.Identity.Name == #Model.UserName)
{
<br />
<ul style="list-style-type: none;">
<li>first name: #Model.FirstName;</li>
<li>username: #Model.UserName</li>
<li>schoolname: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
else
{
<br />
<ul style="list-style-type: none;">
<li>username: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
}
else
{
<h4>need to login</h4>
}
Update: I placed the script only if detail.cshtml. Looks like
there is a problem in this line
var chat = $.connection.notificationHub;
as only the first alert("hi") pops up and not the second...
#model HaifanetMobile.Models.UserModel
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Scripts
{
<script type="text/javascript">
$(function () {
//Create Hub on Air
alert("hi");
var chat = $.connection.notificationHub;
alert("hi1");
//Messages
$messages = $("#messages");
alert("hi2");
//Client Side Method To Access From Server Side Method
chat.client.addMessage = function (frm, msg) {
$messages.append("<br /><b>" + frm + ":</b>" + msg);
}
alert("hi3");
$("#txtMsg").keypress(function (e) {
//when enter
if (e.which == 13) {
alert("hi4");
//get value of input
var input = $(this).val();
//send message to "Server Side Method"
chat.server.sendMessage("#Session.SessionID", input);
//Reset TextBox
$(this).val("");
}
});
//Hub Starting
$.connection.hub.start();
});
</script>
}
<div>Your ID: #Session.SessionID</div>
<input type="text" id="txtMsg" />
<div id="messages">
</div>
<h2>Index</h2>
<span id="mySpanTag"></span>
<br /><br />
#if (Request.IsAuthenticated) {
<h4>user profile: #Model.UserName</h4>
if (User.Identity.Name == #Model.UserName)
{
<br />
<ul style="list-style-type: none;">
<li>first name: #Model.FirstName;</li>
<li>user name: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
else
{
<br />
<ul style="list-style-type: none;">
<li>username: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
}
else
{
<h4>Please login</h4>
}

Opera extension error "Uncaught exception: ReferenceError: Security violation"

I am working on an opera extension. The extension have a popup that will open a website in it.
I get the below error at "xhr.send()" in popup.html file and i can't able to remove it.
"[4/14/2013 12:51:19 PM] JavaScript -
widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html Inline
script thread Uncaught exception: ReferenceError: Security violation
Error thrown at line 30, column 16 in fetchGames() in
widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html:
xhr.send(); called from line 32, column 12 in widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html:
fetchGames(); "
My config file is as below:
<?xml version="1.0" encoding="utf-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" id="http://www.example.org/helloworld">
<name>Hello Extensions!</name>
<description>A simple hello world example</description>
<author href="http://www.twitter.com/dstorey/" email="dstorey#opera.com">David Storey, Opera Software</author>
<icon src="icons/icon-64.png"/>
</widget>
My index.html file is:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Hello World!</title>
<meta charset="UTF-8">
<script>
window.addEventListener( 'load', function(){
var theButton;
var ToolbarUIItemProperties = {
disabled: false,
title: 'Hello World',
icon: 'icons/icon-18.png',
popup: {
href: 'popup.html',
width: 500,
height: 500
}
}
theButton = opera.contexts.toolbar.createItem(ToolbarUIItemProperties);
opera.contexts.toolbar.addItem(theButton);
}, false );
</script>
</head>
<body>
</body>
</html>
My popup.html file is:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body {
background-color: #efefef;
}
</style>
<script>
function fetchGames() {
alert('hello');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = (xhr.responseText);
document.getElementById('list_games').innerHTML = data;
//callback(data);
}
else {
alert('No Games Found');
window.close();
}
}
}
var url = 'http://www.anatomic.us/generate-xml';
xhr.open('GET', url, true);
xhr.send();
};
fetchGames();
function submitForm(obj)
{
var searchKey = document.getElementById('sp').value;
if(searchKey!=null && searchKey!='')
{
obj.setAttribute('action', 'http://www.3d-game.co/'+searchKey);
return true;
// chrome.tabs.create({url: 'http://www.3d-game.co/'+searchKey});
}
else
{
alert('Please Enter your search item');
return false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!-- <div class="header">
<img src="icon.png">
</div>
<br />-->
<div id=content>
<div style='padding-left:10px;'>
<form id=sf method=post action="http://www.3d-game.co/search/" onSubmit="return submitForm(this);" target="_blank">
</form>
</div>
<div id=cat_content>
<div id="list_games" class=list_games>
<img src="loader.gif" border="none" />
<div class="ajax-loader">
<img src="loader.gif" border="none" />
</div>
</div>
</div>
</body>
</html>
Plz help me in removing it.
Add following in the header of the file from where you are fetching the data:
Access-Control-Allow-Origin: *
in config.xml file add this line: to allow any domain httprequest before tab, this solve the problem, if problems persist, open in opera browser tab "opera:config" and select "Users Prefs" and check "Allow File XMLHttpRequest" and restart. if have problem i can send you my opera extension working fine...

login page won't redirect to the secure page

The login form won't redirect to the cloud.php.. i hav created session.. may i know wat is the problem..
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>MyCloud-Login</title>
<?php
//$un = 'abc';
//$pw = 'abc';
$mysql_hostname = "localhost";
$mysql_database = "mycloud_zymichost_register";
$mysql_user = "user";
$mysql_password = "pass";
$conn = mysql_connect($mysql_hostname,$mysql_user,$mysql_password);
mysql_select_db($mysql_database, $conn );
if (isset($_POST['login'])){
//$un = $_POST['name'];
$em = $_POST['email'];
$pw = $_POST['pass'];
//$un = mysql_real_escape_string($un);
$em = mysql_real_escape_string($em);
$pw = mysql_real_escape_string($pw);
$query = "SELECT * FROM Register WHERE email = '$em' AND pass = '$pw'";
//$query = "INSERT INTO Register (name,email,pass) VALUES ('$un','$em','$pw')";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
// Check username and password match
if (mysql_num_rows($result) == 1) {
// Set username session variable
$_SESSION['email'] = $_POST['email'];
// Jump to secured page
header('Location: cloud.html');
}
else {
// Jump to login page
header('Location: login.php');
}
}
?>
<link href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.5.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.js" type="text/javascript"></script>
</head>
<?php
// Inialize session
session_start();
// Check, if user is already login, then jump to secured page
if (isset($_SESSION['email'])) {
header('Location: cloud.php');
}
?>
<body>
<div data-role="page" id="login">
<div data-role="header">
<h1>My Cloud</h1>
</div>
<div data-role="content">Login
<form action="login.php" method="get" name="form">
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="" />
</div>
<div data-role="fieldcontain">
<label for="pass">Password:</label>
<input type="password" name="pass" id="pass" value="" />
</div>
<button type="submit" data-theme="b" name="login" value="submit-value">Login</button>
</form>
</div>
<div data-role="footer">
<h4>Henry</h4>
</div>
</div>
</body>
</html>
The login form won't redirect to the cloud.php.. i hav created session.. may i know wat is the problem..
You cannot call the header function after any output is sent. Visit http://www.w3schools.com/php/func_http_header.asp
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>MyCloud-Login</title>
I seem to remember even blank lines causing issues with this as well. Move the top piece and get rid of blank lines and try again. There may be other issues but that is one of them.

Multiple Google map with php loop

I am trying to dispaly multiple maps with a php loop but i cant get it to work here is the code stripped down...
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAA5iXFaQoABBiRl7JNx5HFuxSa5RD4FXABRIVtLveK1-E6gmai7BR1Y63hhzwAO9ZPoNDgLDBQ_Z6B4Q" type="text/javascript"></script>
</head>
<body onload="load()" onunload="GUnload()">
<?php
if($_POST['select'] == "place"){
$posts = $facebook->api("/search?q=".urlencode($_POST['search'])."&type=".urlencode($_POST['select'])."&center=".urlencode($_POST['center'])."&distance=".urlencode($_POST['distance'])."");
//print_r($posts);
$num = "1";
$num2 = "1";
foreach($posts as $v) {
foreach($v as $v2) { ?>
<div>
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map-<?php echo $num++; ?>"));
map.setCenter(new GLatLng(<?php echo $v2['location']['latitude']; ?>, <?php echo $v2['location']['longitude']; ?>), 13);
}
}
//]]>
<div id="map-<?php echo $num2++; ?>" style="width: 500px; height: 300px"></div>
<p><?php echo $v2['location']['latitude']; ?></p>
<p><?php echo $v2['location']['longitude']; ?></p>
</div>
<?php
}
}
}
}
?>
</body>
</html>
I have tried to put the javascript within the loop but this doesnt work.
Has anyone got any suggestions at the moment it will only show the last map within the loop???
Thanks
I can tell you why it doesn't work. You're redefining the same load() function each time through the loop. So when document loads, and load() gets called, it just displays the last map. By the way, you should also be using google map V3 api instead of V2, but that's a different topic.
Something like this should fix this. First, put this in the <head> section:
<script type="text/javascript">
var loaders = [];
function load() {
for (var i = 1; i < loaders.length; i++) {
loaders[i]();
}
}
</script>
Then change your loop to this:
foreach($posts as $v) {
foreach($v as $v2) { ?>
<div>
<script type="text/javascript">
//<![CDATA[
loaders[<?php echo $num; ?>] = function() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map-<?php echo $num++; ?>"));
map.setCenter(new GLatLng(<?php echo $v2['location']['latitude']; ?>, <?php echo $v2['location']['longitude']; ?>), 13);
}
};
//]]>
<div id="map-<?php echo $num2++; ?>" style="width: 500px; height: 300px"></div>
<p><?php echo $v2['location']['latitude']; ?></p>
<p><?php echo $v2['location']['longitude']; ?></p>
</div>
<?php
}
}