I'm trying to call a function in index.php but I get this error Uncaught ReferenceError: getWidget is not defined. When I call the function in the widget.php it works. How can I get the function getWidget(); to work in index.php?
I also get this warning in index.php
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost/widget.php".
and this error in widget.php
Uncaught SyntaxError: Unexpected token <
Here is index.php and widget.php
index.php
<script type='text/javascript' src='widget.php'></script>
Launch Widget
widget.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="/scripts/jquery-1.7.1.min.js"></script>
<link href="/css/bootstrap/css/bootstrap.css" rel="stylesheet">
<script type='text/javascript' src='/css/bootstrap/js/bootstrap.min.js'></script>
<script type='text/javascript' src='/css/bootstrap/js/bootstrap-transition.js'></script>
</head>
<script type="text/javascript">
var http = getHTTPObject();
function doauth() {
setTimeout("doauth();", 15000);
iframe = document.createElement('iframe');
iframe.id = "hiddenDownloader";
iframe.style.visibility = 'hidden';
iframe.src = "api.php";
http.open("GET", "api.php");
document.body.appendChild(iframe);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse() {
if (http.readyState == 4) {
if (http.responseText != '') {
rslt = http.responseText;
document.getElementById('gw_content').innerHTML = rslt;
first_time = '';
}
// http.onreadystatechange = function(){};
// http.abort();
}
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function getWidget() {
$('#myModal').modal('show');
}
</script>
<div class="modal hide fade" id="myModal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<b style="color: #000;">Modal</b>
</div>
<div class="modal-body">
<h4>Modal</h4>
<p>Instructions...</p><br />
<div id="gw_content">
<body onload="doauth();" />
<img src="wheel-throb.gif">
</div>
</div>
</div>
<button type="button" onclick="getWidget();">Open</button>
There are a few areas of concerns, such as linking a .php extension into a script src attribute, that's causing one of your error message in index.php to appear.
However, to resolve the issue of getWidget not being defined, I would remove the <script> block from widget.php into a separate .js file (ie, yourfile.js) and access it in your index.php file like so,
<script type='text/javascript' src='yourfile.js'></script>
Launch Widget
Also, within widget.php are there any PHP code inside that file? If not, then you should rename it to a .html or .htm extension for clarity.
Related
I've gone through the other answers to this question, but no one seems to be able to apply it universally. Other questions just go unanswered.
Obviously, I'm getting "Can not deserialize instance of String out of START_OBJECT token." in my console. I believe it happens when I attempt to stringify(response) from my websocketdata.
Here is the code.
<?php /**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
*/ ?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<script type="text/javascript"
src='http://martialparks.com/wp-content/themes/js/gamesparks-rt.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/gamesparks.js'></script>
<script type='text/javascript'
src='http://martialparks.com/wp-content/themes/js/gamesparks-functions.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/hmac-sha256.js'></script>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php
wp_head();
?>
</head>
<body <?php body_class() ?>>
<body onload="init()">
<!--Start Header Wrapper-->
<div class="header_wrapper">
<div class="header">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<div class="logo"> <a href="<?php echo esc_url(home_url()); ?>"><img src="<?php if (business_directory_get_option('business_directory_logo') != '') { ?><?php echo esc_url(business_directory_get_option('business_directory_logo')); ?><?php
} else {
echo esc_url(get_template_directory_uri() . '/images/logo.png');
}
?>" alt="<?php bloginfo('name'); ?>" /></a></div>
</div>
<div class="clear"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<div class="clear"></div>
<!--Start Menu Wrapper-->
<div class="menu_wrapper">
<div class="top_arc"></div>
<div class="menu-container">
<div class="container_24">
<div class="grid_24">
<?php business_directory_nav(); ?>
</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="bottom_arc"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<!--End Header Wrapper-->
<div class="clear"></div>
<div class="wrapper">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<br/>
<br/>
<br/>
<input id="apiKey" type="hidden" value="A319082inSk2"/>
<input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
<label for="apiCredential">Api Credential</label><input id="apiCredential"/>
<label for="username">User Name</label><input id="username"/>
<label for="password">Password</label><input id="password"/>
<button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
<button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>
<button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
<button onClick='customEvent()'>Custom Event</button>
<button onClick='testRT()'>Test RT</button>
<i>Special thanks to the awesome team at GameSparks!</i>
<div id="messages"></div>
<br/>
<br/>
User Name
<div id="displayName" style="color: blue;"></div>
Coins
<div id="Coins" style="color: red;"></div>
Exp
<div id="Exp" style="color: green;"></div>
Leader Points
<div id="LeadP" style="color: darkgreen;"></div>
Hero Points
<div id="HeroP" style="color: purple;"></div>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
<h3>Find a Park</h3>
<div id="map"></div>
<script>
function initMap() {
var Velocity = {lat: 38.308101, lng: -85.815464};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: Velocity
});
var marker = new google.maps.Marker({
position: Velocity,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDSHCinT3IVWFCLUudbsMZV6644GNrGiwc&callback=initMap">
</script>
<script type="text/javascript">
//Create a gamesparks object to be used
var gamesparks = new GameSparks();
//Initialse the SDK
function init() {
gamesparks.initPreview({
key: document.getElementById('apiKey').value,
secret: document.getElementById('apiSecret').value,
credential: document.getElementById('apiCredential').value,
onNonce: onNonce,
onInit: onInit,
onMessage: onMessage,
logger: console.log,
});
}
function accountDetailsResponseCreator() {
var response = {
displayName: 'A User',
currencies: {Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p'}
}
accountDetailsResponse(response)
}
//Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
function onNonce(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
}
//Callback to handle when the SDK is initialised and ready to go
function onInit() {
console.log("Initialised");
}
//Callback to handle async messages from the gamesparks platform
function onMessage(message) {
console.log("onMessage");
}
//Response handler examples
function registerResponse(response) {
console.log(JSON.stringify(response));
}
function loginResponse(response) {
console.log(JSON.stringify(response));
}
function accountDetailsResponse(response) {
console.log (JSON.stringify(response));//logs the string to console
document.getElementById("displayName").innerHTML = (response.displayName);
document.getElementById("Coins").innerHTML = (response.currencies.Coins);
document.getElementById("Exp").innerHTML = (response.currencies.Exp);
document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string. I've tried doing each line with semicolons at the end, and all in a group with commas separating them. Both just give me the first variable and delete the rest.
}
function customEvent() {
gamesparks.sendWithData(
"LogEventRequest",
{
eventKey: "FIRST_EVENT",
NUMBER_ATTR: 123,
STRING_ATTR: "this is a string",
JSON_ATTR: {key1: 12, key2: "abc"}
},
function (response) {
console.log(JSON.stringify(response));
}
);
}
var apiKey = "2974660weiMa";
var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
var myTimer = null;
var myRTSession = function () {
};
var numCycles = 0;
myRTSession.started = false;
myRTSession.onPlayerConnectCB = null;
myRTSession.onPlayerDisconnectCB = null;
myRTSession.onReadyCB = null;
myRTSession.onPacketCB = null;
myRTSession.session = null;
myRTSession.start = function (connectToken, host, port) {
var index = host.indexOf(":");
var theHost;
if (index > 0) {
theHost = host.slice(0, index);
} else {
theHost = host;
}
console.log(theHost + " : " + port);
myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
if (myRTSession.session != null) {
myRTSession.started = true;
myRTSession.session.start();
} else {
myRTSession.started = false;
}
};
myRTSession.stop = function () {
myRTSession.started = false;
if (myRTSession.session != null) {
myRTSession.session.stop();
}
};
myRTSession.log = function (message) {
var peers = "|";
for (var k in myRTSession.session.activePeers) {
peers = peers + myRTSession.session.activePeers[k] + "|";
}
console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
};
myRTSession.onPlayerConnect = function (peerId) {
myRTSession.log(" OnPlayerConnect:" + peerId);
if (myRTSession.onPlayerConnectCB != null) {
myRTSession.onPlayerConnectCB(peerId);
}
};
myRTSession.onPlayerDisconnect = function (peerId) {
myRTSession.log(" OnPlayerDisconnect:" + peerId);
if (myRTSession.onPlayerDisconnectCB != null) {
myRTSession.onPlayerDisconnectCB(peerId);
}
};
myRTSession.onReady = function (ready) {
myRTSession.log(" OnReady:" + ready.toString());
if (myRTSession.onReadyCB != null) {
myRTSession.onReadyCB(ready);
}
};
myRTSession.onPacket = function (packet) {
myRTSession.log(" OnPacket:" + packet.toString());
if (myRTSession.onPacketCB != null) {
myRTSession.onPacketCB(packet);
}
};
function testRT() {
myRTSession.stop();
gamesparks.initPreview({
key: apiKey,
secret: apiSecret,
credential: "",
onNonce: onNonceRT,
onInit: onInitRT,
onMessage: onMessageRT,
logger: console.log,
});
}
function onNonceRT(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
}
function onInitRT() {
console.log("Initialised");
gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
sendMatchmakingRequest();
}
});
}
//Callback to handle async messages from the gamesparks platform
function onMessageRT(message) {
//console.log("message " + JSON.stringify(message));
if (message["#class"] === ".MatchFoundMessage") {
var accessToken = message["accessToken"];
var host = message["host"];
var port = message["port"];
myRTSession.stop();
if (myTimer) {
clearTimeout(myTimer);
}
myTimer = setInterval(mainRTLoop, 10);
myRTSession.start(accessToken, host, port);
} else if (message["#class"] === ".MatchNotFoundMessage") {
console.log("MATCH NOT FOUND");
sendMatchmakingRequest();
}
}
function sendMatchmakingRequest() {
gamesparks.sendWithData("MatchmakingRequest",
{
skill: 1,
matchShortCode: "Match_STD"
},
function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
console.log("Match OK...");
}
}
);
}
function mainRTLoop() {
if (myRTSession.started) {
myRTSession.session.update();
var data = RTData.get();
data.setLong(1, numCycles);
myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);
numCycles++;
}
}
</script>
</body>
</html>
For the life of me, I have no idea what is happening or how to fix it. The problem pops up when I activate a button that references line 173
function loginResponse(response) {
console.log(JSON.stringify(response));
}
But don't let that affect your impartiality. I compared this code to earlier versions of the code I have and could not identify a change in any of my functions.
Well, bottom line is this: When you are an idiot, don't post questions to stackoverflow. No one will respond. Not because they are mean, but because learning the basics is important.
So the problem originated for me in the top of my code with this:
<button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>
Weird, right? Not really. What had done was try to alter the input for the authentication request to match my html element inputs (see where my elements are labeled as username and password?) It didn't work, and I obviously just shelved that and moved on...and forgot. What I did was change "username" to "testuser". This matched the value I was trying to authenticate. Now, my baby is returning values on my testuser, and running like a dream.
Thanks for the tough love, stackoverflow.
When we click on an anchor tag it should call the jquery function which is in external file but i don't know how to call a click function externally.
This is my code:
php
<html>
<head>
<script type="text/javascript" src="js/loc.js'">
</script>
</head>
<body>
<div id="locname">
<ul class="loct" >
<li >
<a href=# class="c" >Camp
</a>
</li>
</ul>
</div>
</body>
</html>
js file
$(document).ready( function() {
var $flag='0';
$(".c").on("click",function(event){
var $trigger = $(".c");
if($trigger !== event.target &&
!$trigger.has(event.target).length)
{
if($flag=='0')
{
$flag='1';
$(".co").fadeToggle("fast");
}
else if($flag=='1')
{
$flag='0';
$(".co").fadeToggle("fast");
}
}
});
}
}
Above code is working fine now
First of all, you do not need to wrap your JS code in <script></script> if your file's extension is .js
Solution: Update your JS file with the following code
var $flag='0';
function myFunction(event){
var $trigger = $(".c");
if($trigger !== event.target &&
!$trigger.has(event.target).length)
{
if($flag=='0')
{
$flag='1';
$(".co").fadeToggle("fast");
}
else if($flag=='1')
{
$flag='0';
$(".co").fadeToggle("fast");
}
}
};
Your anchor tag should be:
Camp
Also, since you're using jQuery, make sure you include jQuery library as well.
You can do like this
HTML file
<html>
<head>
<script type="text/javascript" src="<?php echo base_url('js/loc.js');?>">
</script>
</head>
<body>
<div id="locname">
<ul class="loct" >
<li >
<a href=# class="c" onclick= "externalFunction(this);">Camp
</a>
</li>
</ul>
</div>
</body>
</html>
JS file
<script type="text/javascript">
$(document).ready( function() {
var $flag='0';
function externalFunction(event){
var $trigger = $(".c");
if($trigger !== event.target &&
!$trigger.has(event.target).length)
{
if($flag=='0')
{
$flag='1';
$(".co").fadeToggle("fast");
}
else if($flag=='1')
{
$flag='0';
$(".co").fadeToggle("fast");
}
}
});
}
}
<script>
I thing it will help you.
I am new to this client variable to server variable transfer process.
Essentially I have a Google maps api function and have a marker on a map to represent a username in a users table (MySQL) of my PHP web app. When I double click on that map marker my Jquery function is popping up a modal and I am able to get the username in an id/name element (chosenUser) in a . However, I now need to be able to access this value in a PHP variable ($chosenUser) without any "submit" or page refresh, so that I can invoke my PHP function - getUserChannelID($chosenUser), and continue with the rest of the logic.
My disconnect is the ability to be able to access that value coming through on the id/name as #chosenUser and transfer it to a PHP variable $chosenUser without a "submit" or page refresh. All the code below is on the same page.
I am reading about the use of AJAX to do this in SF posts but since I quite the infant with AJAX I am getting confused on how exactly this can be done on the same page without a form "submit" or page refresh.
Can you please help correcting the code below so that I can get that value in #chosenUser to the PHP variable $chosenUser?
Here's my code all in the same PHP file.
<?php
require_once("classes/autoload.php");
$db = new Database();
....
?>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" ></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid" style="margin: 0 auto;">
<div style="height: 100%; position: relative; top:30px;">
<div id="map" style="height: 100%;"></div>
</div>
<div class="modal fade" id="showChannel" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Channel Preview</h4>
</div>
<div class="modal-body">
<div>
<input type="hidden" id="chosenUser" name="chosenUser" value="">
<!-- This is where I need help. How do I transfer that value I am getting for "chosenUser" above into the PHP variable $chosenUser - ideally the code in the next line would need to be executed -->
<?php $channelId = $db->getUserChannelID($chosenUser); ?>
.....
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script src="multiple_marker/oms.js"></script>
<script type="text/javascript">
var mapMarkers = [];
var infowindow = null;
var infowindowOpen;
var map, oms;
var gm = google.maps;
var markerIcons = new Array();
var gmarkers = [];
function getCoords() {
$.ajax({
url: "markers.php", // this markers.php provides the value of "Locations" array used below
type: "POST",
data: {
foo: "bar"
},
dataType: "json",
success: function (returnedData) {
console.log(returnedData);
if(!spiderify)
moveMarkerMap(returnedData);
//window.setInterval(getCoords, 10000);
window.setTimeout(getCoords, 2000);
}
});
}
function MarkerMap(json) {
var iconBase;
oms.addListener('click', function (marker) {
console.log('clicked');
});
if ((json.Locations.length > 0)) {
for (i = 0; i < json.Locations.length; i++) {
var location = json.Locations[i];
var username = location.username; // I am getting the value of username here
var myLatlng = new gm.LatLng(location.Lat, location.Long);
var marker = new gm.Marker({
position: myLatlng,
map: map,
username: username,
});
var infowindow = new gm.InfoWindow();
var div = document.createElement('DIV');
gm.event.addListener(marker, 'dblclick', (function (marker, div, infowindow) {
return function () {
$('#showChannel').modal('show');
$('#chosenUser').val(marker.username); //passing the value of marker.username to the modal input id/name="chosenUser"
};
})(marker, div, infowindow));
gmarkers[id] = marker;
}
}
window.map = map;
window.oms = omg;
}
gm.event.addDomListener(window, 'load', initialize);
</script>
Well, you can't exactly communicate between PHP and JS in the way you're thinking of. PHP is executed while the page is loading, before any content is displayed, before any javascript is even sent to the client, so it's impossible to do it as you wish.
What you can do is call a PHP script once the page is finished loading, using javascript. You can do this whenever you like, using a delay loop, when clicking a button, any way you can call your javascript function. That way you can send information from javascript to PHP, and when the PHP script finishes running it can report back information to javascript.
You want a variable from js in PHP, there are multiple ways of doing this, such as POST or GET requests. I'll post an example using POST, which is the same thing you'd use to send a form. You'll need to include jQuery for this to work.
JS
var myVar = "my info";
var myVar2 = "my other info";
$.post("myscript.php", {
info1: myVar,
info2: myVar2
}, function(answer) {
// answer will contain whatever the PHP script printed
// in this example answer will be "success"
alert(answer);
} );
PHP
$var1 = $_POST['info1'];
$var2 = $_POST['info2'];
if(!empty($var1) && !empty($var2))
{
echo "success";
}
It's up to you to implement it now.
I have this Star Rating system right. When you click on a star it should pass a value into the function. Then using AJAX it posts it to an external PHP file. The only problem is that when it gets to the PHP file it comes as null or no value.
I will try to echo the $_POST['vote'] variable in an alert box using AJAX and it is blank so it doesn't come back as "NULL" or "0" it's just nothing. I'm not sure where I'm losing the value because I can track it all the way to the send() function. Anyone see a problem?
HTML:
<style type="text/css">
#container{margin: 10px auto;width: 500px;height: 300px;background-color: gray;}
#starContainer{padding-top:20px;margin:0 auto;width:150px;}
.box{height:28px;width:30px;float:left;position:relative;z-index:5;cursor:pointer;}
.star{background-image:url('emptyStar.png');background-repeat:no-repeat;}
.starHover{background-image:url('goldStar.png');background-repeat:no-repeat;}
#voteBar{float:left;height:28px;background-color:#dbd923;position:relative;top:-28px;z-index:1;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.box').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('starHover');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('starHover');
}
);
});
function Cast(vote)
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert(xmlhttp.responseText);
var json = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "process.php", true);
xmlhttp.send('vote=' + vote);
}
</script>
</head>
<body>
<div id="container">
<center>
<div id="starContainer">
<div class="box star" onclick="Cast(1)"></div>
<div class="box star" onclick="Cast(2)"></div>
<div class="box star" onclick="Cast(3)"></div>
<div class="box star" onclick="Cast(4)"></div>
<div class="box star" onclick="Cast(5)"></div>
<div id="voteBar"></div>
</div>
</center>
</div>
</body>
</html>
PHP:
<?php
$vote = $_POST['vote'];
$totalVoteValue = 0;
$amtVotes = 1;
$width = (($totalVoteValue + (($vote - $totalVoteValue) / $amtVotes)) / 5) * 150;
echo $width;
?>
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
adding this may help (before send after open)
You are already using jquery (a very very very old version if i may say..), why not use it's built in ajax handler?
http://api.jquery.com/jQuery.post/
$.post('process.php', {vote: vote}, function(data) {
$('.result').html(data);
});
I've just started using Gigya to allow users to connect to my site. I already have a login system so I just want to connect existing users to the Gigya service.
To do this I have called the "gigya.services.socialize.notifyLogin" function which returns a Gigya User object with the UID provided by my site. [fig 1]
Do I need to do anything with this User object, like add it to a cookie or is it just for reference.
The problem that Im having is on another page, I want to allow users to connect to their social media accounts. I use the "showAddConnectionsUI" function passing my api key, but the returned object does NOT have the User object in, although the documentation says it should. How do I get the users conenctions and the key information from this function. Do I need to send any additional information along with my api key. [fig 2]
I have spent several days reading the wiki, documentation and forum for advice but I am still stuck. Any help would be greatly appreciated. Thanks in advance, Ben
[fig 1]
<script type="text/javascript" src="http://cdn.gigya.com/js/socialize.js?apiKey=<?php echo $key; ?>"></script>
<script type="text/javascript">
var gigyaConf = { APIKey: "<?php echo $key; ?>", signIDs: "true" }
var signature = "<?php echo $signature; ?>";
var siteUID = "<?php echo $userId; ?>";
var timestamp = "<?php echo $timestamp; ?>";
var gigyaParams =
{
siteUID:siteUID,
timestamp:timestamp,
signature:signature,
callback:gigyaNotifyLoginCallback
};
gigya.services.socialize.notifyLogin(gigyaConf, gigyaParams);
function gigyaNotifyLoginCallback(eventObj) {
if ( eventObj.errorCode != 0 ) {
alert('Gigya Error: ' + eventObj.errorMessage);
}
}
</script>
[fig 2]
<script type="text/javascript" lang="javascript" src="http://cdn.gigya.com/JS/socialize.js?apikey=<?php echo $key; ?>"></script>
<script>
var conf = { APIKey: '<?php echo $key; ?>', signIDs: 'true' };
$(document).ready(function(){
gigya.services.socialize.getUserInfo(conf, { callback: renderUI });
gigya.services.socialize.addEventHandlers(conf,
{
onConnectionAdded: renderUI,
onConnectionRemoved: renderUI
});
});
</script>
<script>
function renderUI(res) {
if (res.user != null && res.user.isConnected) {
document.getElementById("name").innerHTML = res.user.nickname;
if (res.user.thumbnailURL.length > 0)
document.getElementById("photo").src = res.user.thumbnailURL;
else
document.getElementById("photo").src = "http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif";
document.getElementById("profile").style.display = "block";
} else {
document.getElementById("profile").style.display = "none";
}
}
</script>
<div id="content">
<h5>Step 1: Connect</h5>
<div id="divConnect"></div>
<script type="text/javascript">
gigya.services.socialize.showAddConnectionsUI(conf, {
height:65,
width:175,
showTermsLink:false,
hideGigyaLink:true,
useHTML:true,
containerID: "divConnect"
});
</script>
<br />
<h5>Step 2: See User Info</h5><br />
<div id=profile style="display:none;">
<img id="photo" src="" width="60" />
<br />
<span id="name" ></span>
</div>
</div>
Any help, advice, code snippits that would help will be greatly appreciated
Re: your first question, not required to do anything special with the Gigya User object. It's for your reference.
Re: your code, I can't tell if you're using JQuery but I was getting an error with your $(document).ready function. I modified your code slightly by adding body onLoad and everything worked. This assumes you have connected with a provider. Here's my code... hope it helps:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" lang="javascript" src="http://cdn.gigya.com/JS/socialize.js?apikey=<?php echo $key; ?>"></script>
<script>
var conf = { APIKey: '<?php echo $key; ?>', signIDs: 'true' };
function onLoad() {
gigya.services.socialize.getUserInfo(conf, { callback: renderUI });
gigya.services.socialize.addEventHandlers(conf,
{
onConnectionAdded: renderUI,
onConnectionRemoved: renderUI
});
}
</script>
<script>
function renderUI(res) {
if (res.user != null && res.user.isConnected) {
document.getElementById("name").innerHTML = res.user.nickname;
if (res.user.thumbnailURL.length > 0)
document.getElementById("photo").src = res.user.thumbnailURL;
else
document.getElementById("photo").src = "http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif";
document.getElementById("profile").style.display = "block";
} else {
document.getElementById("profile").style.display = "none";
}
}
</script>
<body onload="onLoad()">
<div id="content">
<h5>Step 1: Connect</h5>
<div id="divConnect"></div>
<script type="text/javascript">
gigya.services.socialize.showAddConnectionsUI(conf, {
height:65,
width:175,
showTermsLink:false,
hideGigyaLink:true,
useHTML:true,
containerID: "divConnect"
});
</script>
<br />
<h5>Step 2: See User Info</h5><br />
<div id=profile style="display:none;">
<img id="photo" src="" width="60" />
<br />
<span id="name" ></span>
</div>
</div>
</body>
</html>