I’m really hoping some one here will be able to help me with this!
I’m making a Facebook Canvas game and I’m having difficulty inputting the player’s details (Facebook ID, first name, last name, email etc) into my database.
Here’s the process I’m trying to make happen:
When a player arrives at the game’s homepage, I want the game to check the user’s Facebook ID against the database to see if the player’s id, and other details are there, this will tell me if they’ve played the game before. If their id/details are not contained in the database then I want them to be inserted, and I want a Javascript message box to appear which will contain a short tutorial on the game. If the check shows that the player’s details are already in the database, then I want no message box to appear and the page should be unchanged.
I’m trying to get this to work by calling a Javascript function using “onload” in the html. The Javascript function contains code to get the user’s details from Facebook, and contains some AJAX which calls a PHP script which inserts the details into the database. This works perfectly if I use “onclick” or “onmouseover” inside the tag (when I try these two methods the user’s details get entered correctly and the message box appears). However, when I try using the “onload” method, while it does create a row in the database, every cell is empty, it seems like it’s executing the code correctly but the AJAX call doesn’t have time to get the user’s details from Facebook, and so the row gets created with no values.
This is the correctly working Javascript/AJAX funtion, and the PHP it calls:
function getUserDetails() {
FB.api('/me', function(response) {
var userid = response.id;
var userfirst_name = response.first_name;
var userlast_name = response.last_name;
var useremail = response.email;
var userbirthday = response.birthday;
var usergender = response.gender;
$.ajax({
url: 'insertuserdetails.php',
data: {'userid' : userid, 'userfirst_name' : userfirst_name, 'userlast_name' : userlast_name, 'useremail' : useremail, 'userbirthday' : userbirthday, 'usergender' : usergender},
type: "POST",
}).done(function( msg ) {
alert("php file called, A TUTORIAL COULD GO HERE"+msg);
});
});
}
The PHP:
<?php
session_start();
require_once '/facebook-php-sdk-v4-4.0-dev/autoload.php';
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookSignedRequestFromInputHelper;
use Facebook\FacebookCanvasLoginHelper;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
FacebookSession::setDefaultApplication('MYAPPID', 'MYAPPSECRET');
$servername = "XXX";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$userid = $_POST['userid'];
$userfirst_name = $_POST['userfirst_name'];
$userlast_name = $_POST['userlast_name'];
$useremail = $_POST['useremail'];
$userbirthday = $_POST['userbirthday'];
$usergender = $_POST['usergender'];
$sql="INSERT INTO player (facebook_id, first_name, last_name, email, birthday, gender) VALUES
('$userid', '$userfirst_name', '$userlast_name', '$useremail', '$userbirthday', '$usergender')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I could just use “onclick” and “onmouseover” but this means that every time these actions are performed by the user, multiple calls will be made to the database, that’s really messy and would probably slow the game down a lot. Ideally I’d like for the Javascript function to be called only once per session (when the page loads).
The "onload" in the html that results in an empty row being created:
<body onload="getUserDetails()">
I’m not sure why "onload" returns empty values while the other two methods don’t. I was wondering if delaying a function by a few seconds would solve the problem? But I’m really not sure, so I thought I’d ask for help here. :) Thanks in advance!
Code used to initialize the Facebook Javascript API:
$( document ).ready(function() {
FB.init({
appId: MYAPPID,
frictionlessRequests: true,
status: true,
version: 'v2.1'
});
FB.Event.subscribe('auth.authResponseChange', onAuthResponseChange);
FB.Event.subscribe('auth.statusChange', onStatusChange);
UPDATE: I’ve marked @floor’s answer as working because it has solved my problem. There’s just one issue I’m having now but it doesn’t directly involve the AJAX issue.
I thought I’d be able to do something simple like check if the AJAX+PHP insertion was successful and if so, then a tutorial pop-up would appear, if not, then it would mean that user’s id is already in the database and so no tutorial would appear.
My problem is that this check was always coming back as successful (because the AJAX call is always successful, regardless of whether the SQL insert completes successfully or not), so I was asking the wrong question, instead I needed to add an echo at the end of my SQL/PHP script, whose value is determined by the success or failure of the insert statement. I then need to add a success check in the AJAX call which will initiate the popup, or not, depending on the echo it receives back from the PHP script.
The code I’m using to do this is: AJAX:
$.ajax({
url: 'insertuserdetails.php',
data: {'userid' : userid,
'userfirst_name' : userfirst_name,
'userlast_name' : userlast_name,
'useremail' : useremail,
'userbirthday' : userbirthday,
'usergender' : usergender},
type: "POST",
success: function(response){
if(response==1){
alert( "Success!");
}else{
alert( "Failed!" );
}
}
});
And the PHP to send the success/fail echo:
//If the SQL insert statement completed correctly...
if($sql){
$verify=1;
}else{
$verify=0;
}
echo $verify;
I must have an error in this code, because the popup always displays "Failed!", it does this both when the Insert is successful (when I run the script with an empty database), and when it's unsuccessful (when the database isn't empty/when the row already exists before running the script).
The PHP should be echoing "1", so the AJAX should output "Success!", but it isn't. Can anyone see an error in the check I'm trying to perform?