I'm using Ratchet PHP for a chat.
I need to be able to display how many users are online.
So in my Chat.php file:
public function onOpen(ConnectionInterface $conn)
{
$count = $this->clients->count() + 1;
print_r($count);
$conn->countClient = $count;
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
Since this function is called every time a new connection is made.. I chose to make my count there but... correct me if I'm wrong ;)
print_r($count);
Give give me 1... even if I have multiple users connected.
But I also struggle with the JS part:
<script>
function connect() {
var conn = new WebSocket('ws://localhost:8080?token={{ user.user_id }}');
// OPEN THE CONNECTION
conn.onopen = function (e) {
console.log("Connection established!", );
};
}
</script>
How can I pass the value count (attach to the conn object in my PHP function) ?
Thanks for any advice or help
Related
I am working on Tokbox video calling process. Now I am using the sample kit of Tokbox which is working properly but it is showing me all active user video.
but I need one user can video calling to another user.
I mean I need one to one video calling process. Is It possible in Tokbox. So please help to solve out it.
This is My code
use Slim\Slim;
use Gregwar\Cache\Cache;
use OpenTok\OpenTok;
if(!empty($userid))
{
$autoloader = __DIR__.'/../../../component/tokbox/vendor/autoload.php';
if (!file_exists($autoloader)) {
die('You must run `composer install` in the sample app directory');
}
require($autoloader);
// PHP CLI webserver compatibility, serving static files
$filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
// Initialize Slim application
$app = new Slim(array(
'templates.path' => __DIR__
));
// Intialize a cache, store it in the app container
$app->container->singleton('cache', function() {
return new Cache;
});
// Initialize OpenTok instance, store it in the app contianer
$app->container->singleton('opentok', function () {
return new OpenTok('***', '****');
});
// Store the API Key in the app container
$app->apiKey = '45833942';
$id=$this->uri->segment('3');
$urlname=$this->uri->segment('4');
// Configure routes
$app->get('/home/livechat/'.$id.'/'.$urlname.'/', function () use ($app) {
// If a sessionId has already been created, retrieve it from the cache
$sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
// If the sessionId hasn't been created, create it now and store it
$session = $app->opentok->createSession();
return $session->getSessionId();
});
// Generate a fresh token for this client
$token = $app->opentok->generateToken($sessionId);
/*$this->db->select('activemember');
$this->db->from('pshy_videocat');
$psychics=$this->db->get();
$totaluseractive= $psychics->row();
$totalactivevideouser=$totaluseractive->activemember;*/
?>
<input type="hidden" id="connectionCountField" value="0"></input>
<!--button onclick="myFunction()">Toggle Video</button-->
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://static.opentok.com/v2/js/opentok.js" charset="utf-8"></script>
<script charset="utf-8">
var publisher;
var connectionCount = 0;
var apiKey = '<?php echo '45833942'; ?>';
var sessionId = '<?php echo $sessionId; ?>';
var token = '<?php echo $token; ?>';
var subscribeoptions = {width: 664, height: 421, insertMode: 'append'}
var session = OT.initSession(apiKey, sessionId)
.on('streamCreated', function(event) {
session.subscribe(event.stream,'myPublisherDiv', subscribeoptions);
})
.connect(token, function(error) {
var publisherOptions = {
insertMode: 'append',
width: 150,
height: 150,
publishAudio:true,
publishVideo:true,
name: "You"
};
publisher = OT.initPublisher('mycam', publisherOptions);
session.publish(publisher);
});
session.on("connectionCreated", function(event) {
connectionCount++;
displayConnectionCount();
});
session.on("connectionDestroyed", function(event) {
connectionCount--;
displayConnectionCount();
});
function displayConnectionCount() {
document.getElementById("connectionCountField").value = connectionCount.toString();
/*var newdata=connectionCount.toString();
$.ajax({
url:$('#baseUrl').val()+"home/updateactiveuser",
type:'post',
data: {newdata:newdata}
})*/
}
var enableVideo=true;
function myFunction() {
if(enableVideo)
{
publisher.publishVideo(false);
enableVideo=false;
} else
{
publisher.publishVideo(true);
enableVideo=true;
}
}
</script>
<?php
});
$app->run();
}
?>
Thanks
Here is a sample code. I've not used SLIM for this. But this can be done with Slim also. I've executed the script 5 times & each time I got a unique Session-Id.
Session Id Received -
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ0NzU0NH5KNk9Gcy9FSktPSlUwdldUbURwazJ0Umd-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ3ODMzM35rWWU5NDV1ZjZPMGhLc3pCS3pRSERJY0h-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ5NTcwOX5kc0Q3NDBjQSthOWJaMEk1eUllU3dCY0t-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzUwNzExOH5NMEZuZWRyejBZYnZRVk1zSEczNldocmV-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzUxNzE3NH5Yc0hyMUlacmFqK25pVzhXNDI5NTV6eDB-QX4
Vanilla PHP Script -
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require 'vendor/autoload.php';
use OpenTok\OpenTok;
$apiKey = '45833942';
$apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';
$opentok = new OpenTok($apiKey, $apiSecret);
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;
// An automatically archived session:
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $opentok->createSession($sessionOptions);
// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();
echo "Session Id Got : $sessionId";
SLIM Version -
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use OpenTok\OpenTok;
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;
require 'vendor/autoload.php';
$app = new \Slim\App;
$container = $app->getContainer();
$container['opentok'] = function ($c) {
$apiKey = '45833942';
$apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';
$opentok = new OpenTok($apiKey, $apiSecret);
return $opentok;
};
$app->get('/', function (Request $request, Response $response) {
// An automatically archived session:
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $this->opentok->createSession($sessionOptions);
// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();
$response->getBody()->write("Session Id Got : $sessionId");
return $response;
});
$app->run();
Hope, it'll help you.
Ref : https://tokbox.com/developer/sdks/php/
Looks like you have based your code on the OpenTok Hello World PHP sample. This sample is written to support a single session only, for demonstration purposes. Your issue here is that you are retrieving the same key (sessionId) from cache every time, which is what the sample does.
You are close. The simplest way to extend this sample to multiple sessions is to store your new session IDs in the cache as different keys. You need to change your code to use different key for storing and retrieving session ID. So, you can change the cache retrieval logic from:
<?php
$sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
# ...
}
?>
to something like:
<?php
# Here we add `$id` from the URI segment to create a unique key
# Notice the change in the key name to `'session' . $id'`
$sessionId = $app->cache->getOrCreate('session' . $id, array(), function() use ($app) {
# ...
}
?>
At the simplest, your code needs to map your application's live chat ID to an OpenTok session internally. Everytime you request for a new livechat ID, it will create a new OpenTok session and store the new OpenTok session ID internally for that livechat ID.
So, you should have two different sessions if you request:
/home/livechat/foo/bar
/home/livechat/baz/bar
Bonus
A quick tip on creating OpenTok sessions: This is all you need to create a new session using OpenTok PHP SDK:
<?php
use OpenTok\OpenTok;
$apiObj = new OpenTok($API_KEY, $API_SECRET);
# This function creates an OpenTok session and returns a new session ID
function createOTSession() {
$session = $apiObj->createSession(array('mediaMode' => MediaMode::ROUTED));
return $session->getSessionId();
}
?>
Everytime you call $apiObj->createSession(), it creates a new session and you can access the session id by calling getSessionId() on the returned object. If you have a function like createOTSession() above, you can call that function from a route that needs to creates new sessions.
See: Creating OpenTok sessions in PHP
I am new to Web Development. I'm creating a web application where I need to use ZMQ Library for receiving data continuously and update a html table in real-time.
I tried a lot and just succeeded in receiving a single data packet. Later I'm calling the function recursively to get all data packets. But, by the time I call the function, I already lost some packets in the gap.
Following is the javascript function I'm using in index.php and test.php for receiving data using ZMQ:
Javascript function inside index.php
function samp(result)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var x=document.getElementById('PageTable');
var rowCount = document.getElementById("PageTable").rows.length;
for (var i = 0; i < rowCount; i++)
{
if(x.rows[i].cells[2].innerHTML == xmlhttp.responseText)
{
x.rows[i].cells[3].innerHTML=xmlhttp.responseText;
}
}
samp(result);
}
};
xmlhttp.open("GET","test.php?q="+result,true);
xmlhttp.send();
}
test.php for receiving data using ZMQ
<?php
$Params = $_REQUEST["q"];
$context = new ZMQContext();
$subscriber = new ZMQSocket($context, ZMQ::SOCKET_SUB);
$subscriber->connect("tcp://localhost:5000");
$mnemonic = explode(" ", $Params);
foreach ($mnemonic as $value)
{
if($value!="")
{
$subscriber->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, $value);
}
}
$contents = $subscriber->recv();
echo $contents;
I even tried running the php script inside the javascript function but had no luck. I also tried using an infinite loop in test.php to receive data as following but now as the loop is not ended I stopped receiving even a single packet.
while(true)
{
$contents = $subscriber->recv();
echo $contents;
}
Any help to solve this problem or even suggestion to any different approach is highly appreciated. Thank you.
I'm designing a chatroom in ratchet websockets to be as responsive as possible.
It knows when a user leaves the page, and everything like that.
But if a user/client for example loses its connection with the server, the issue is the client cant let the server know it has disconnected, because it has already disconnected and cant send the server a message. So how do I track when a chat client has lost their internet connection and is no longer online?
Two possible solutions I can think of:
server polls the clients once every 15 mins to half hour to check to see who is online. Clients who do not respond get disconnected. Is this possible to do without interrupting everything else going on in php? if so how? and where do I put the code? I saw something about addPeriodicTimer() from LoopInterface but im not sure if that would do the job or where the function would fit into my code.
Also does it call sleep() function because that would not be good. I still want other tasks happening in the background while this function is on a timer (if possible in php)
onClose() method in php
Can this detect when a user has really disconnected in every circumstance? If so, when this event fires off, how can I find out which user was disconnected? it only passes a ConnectionInterface and no message.
Sorry, im still new to the ratchet library and still trying to work out how to achieve this task.
my code for server.php:
<?php
require($_SERVER['DOCUMENT_ROOT'].'/var/www/html/vendor/autoload.php');
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
$server = IoServer::factory(new HttpServer(new WsServer(new Chat)), 8080);
$server->run();
?>
code for app.js
// JavaScript Document
var chat = document.getElementById("chatwindow");
var msg = document.getElementById("messagebox");
var refInterval = 0;
var timeup = false;
var awaytimer;
var socket = new WebSocket("ws://52.39.48.172:8080");
var openn = false;
function addMessage(msg){
"use strict";
chat.innerHTML += "<p>" + msg + "</p>";
}
msg.addEventListener('keypress', function(evt){
"use strict";
if(evt.charCode != 13)
return;
evt.preventDefault();
if(msg.value == "" || !openn)
return;
socket.send(JSON.stringify({
msg: msg.value,
uname: nme,
uid: id,
tag: "[msgsend]"
}));
msg.value = "";
});
socket.onopen = function(evt) {
openn = true;
socket.send(JSON.stringify({
uname: nme,
uid: id,
tag: "[connected]"
}));
};
socket.onmessage = function(evt) {
var data = JSON.parse(evt.data);
if(data.tag == "[connected]")
{
addMessage(data.uname + " has connected...");
}
else if(data.tag == "[bye]")
{
addMessage(data.uname + " has left the room...");
if(data.uname == nme)
socket.close();
}
else if(data.tag == "[msgsend]")
{
addMessage(data.uname + ": " + data.msg);
}
};
window.onfocus = refPage;
function refPage()
{
if(timeup == true)
{
if(refInterval == 1)
{
refInterval = 0;
location.reload();
}
}
else
{
clearTimeout(awaytimer);
}
timeup = false;
}
window.onblur = timelyExit;
function timelyExit()
{
refInterval = 1;
// change this to trigger some kind of inactivity timer
awaytimer = setTimeout(function(){socket.send(JSON.stringify({
uname: nme,
uid: id,
tag: "[bye]"
})); timeup=true; }, 900000);
}
window.onoffline = window.onunload = window.onbeforeunload = confirmExit;
function confirmExit()
{
socket.send(JSON.stringify({
uname: nme,
uid: id,
tag: "[bye]"
}));
socket.close();
}
socket.onclose = function() {
openn = false;
//cant send server this message because already closed.
/*
socket.send(JSON.stringify({
uname: nme,
uid: id,
tag: "[bye]"
}));
*/
socket.close();
};
Code for chat.php
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_id($_GET['sessid']);
if(!session_id)
session_start();
$userid = $_SESSION["userid"];
$username = $_SESSION["username"];
$isadmin = $_SESSION["isadmin"];
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
}
public function onMessage(ConnectionInterface $conn, $msg)
{
$msgjson = json_decode($msg);
$tag = $msgjson->tag;
if($tag == "[msgsend]")
{
foreach($this->clients as $client)
{
$client->send($msg);
}
}
else if($tag == "[bye]")
{
foreach($this->clients as $client)
{
$client->send($msg);
}
onClose($conn);
}
else if($tag == "[connected]")
{
//store client information
//send out messages
foreach($this->clients as $client)
{
$client->send($msg);
}
}
}
public function onError(ConnectionInterface $conn, Exception $e)
{
echo "Error: " . $e->getMessage();
$conn -> close();
}
}
?>
Edit: just tested and confirmed onClose() method doesnt fire when internet connection is terminated.
is there a way i can still go about the first solution?
This best solution for detecting disconnected clients would be event based and does not poll the clients at all. This approach would be your second solution, and also models itself nicely around the asynchronous nature of WebSocket message passing.
It is however possible as you state that some naughty clients in certain cases may not notify the socket server of their disconnection and leave it 'hanging', so to speak. In this case, I would suggest to not try to implement the polling trigger within the Socket Server itself and instead initiate the polling via a separate, server-side client that is triggered via cron or other task scheduler and instructs the socket server to initiate a request to poll all connected clients.
For more information on constructing server-side clients, see this question of mine for which I was also able to find some solutions.
In order to determine who sent the disconnect message, I would suggest going away from using just SplObjectStorage inside of the Ratchet\MessageComponentInterface implementation you have and instead wrap a simple array inside of another class, so something like this:
class MyClientList
{
protected $clients = [];
public function addClient(Connection $conn)
{
$this->clients[$conn->resourceId] = [
'connection' => $conn,
];
return $this;
}
public function removeClient(Connection $conn)
{
if(isset($this->clients[$conn->resourceId])) {
unset($this->clients[$conn->resourceId]);
}
return $this;
}
public function registerClient(ConnectionInterface $conn, array $userData)
{
if(isset($this->clients[$conn->resourceId])) {
$this->clients[$conn->resourceId] = array_merge(
$this->clients[$conn->resourceId],
$userData
);
}
return $this;
}
public function getClientData(ConnectionInterface $conn)
{
return isset($this->clients[$conn->resourceId]) ?
$this->clients[$conn->resourceId] :
null
;
}
}
At some point shortly after a user first connects, your client should send a socket message to the server and instruct the server to now register the identity of the client with additional information (in your case you are attempting to identify a uname and uid properties). By indexing against the connection id, you should be able to use this implementation to divine the identity of all messages originating from clients after they have sent in the initial registration message.
UPDATE:
I've found out what's been causing this problem. The webpage has a piece of Javascript contained inside its body which is preventing the Javascript body onload= function from executing in Firefox, Safari and IE. Chrome is able to run both without problems. To solve this I've tried moving the script inside <head>..</head> however that script will not work for me there, it seems like it needs to be inside the body (I've tried calling it from an external .js file too but it won't work from there either). This is the body onload function along with the problematic script:
<html>
<head>
//some Javascript & Style files are included here..
</head>
<body onload="getUserDetails()">
<script>
window.onload = function() {
$('#selectAllFriends').change(function(){
if (this.checked) {
$('#mfsForm :checkbox').each(function() {
this.checked = true;
})
}
else {
$('#mfsForm :checkbox').each(function() {
this.checked = false;
})
}
});
}
</script>
//rest of page body is contained here...
</body>
</html>
This script is needed as part of a Facebook Multi-Friend Selector. I think maybe the problem is to do with running window.onload and body onload= at the same time? Is there a way to maybe delay the Multi-Friend Selector script for a couple of seconds to let the body onload= function to run first, and would that resolve the problem?
Original Question:
I have a Javascript function which gets called on page load. Inside this function there’s a call to Facebook’s Graph API, this call gets user details from Facebook, and then passes them by an AJAX post to a PHP script.
This is the Javascript I'm using:
function getUserDetails() {
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
if (response.error) {
console.log('Error - ' + response.error.message);
}
else {
var userid = response.id;
var userfirst_name = response.first_name;
var userlast_name = response.last_name;
var useremail = response.email;
var usergender = response.gender;
$.ajax({
url: 'insertdetails.php',
data: {'userid' : userid,
'userfirst_name' : userfirst_name,
'userlast_name' : userlast_name,
'useremail' : useremail,
'usergender' : usergender},
type: "POST",
success: function(response){
if(response==1){
alert( "Insert Successful!");
}
else{
alert( "Insert Failed!" );
}
}
});
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
}
Originally the PHP script contained two basic Insert statements which inserted these details into two tables in my database. This worked perfectly, but it wasn’t secure, so yesterday I wrote a PDO prepared transaction statement instead. I later found out that my database engine (MyISAM) doesn’t support PDO transaction statements, so I decided instead to run two queries (that would insert data into the two tables) inside the same PHP script instead (I know this isn’t best practice but I couldn’t find a way to get PDO transactions to work with MyISAM).
This is the part that’s confusing to me: when testing the new PHP file, I find that it works perfectly when I open the page in Chrome, however it doesn’t work with Firefox, IE, or Safari.
The PHP script
<?php
$servername = "myserver";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabase";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters for 1st insert
$stmt = $conn->prepare("INSERT INTO user (fb_id, f_name, l_name, email, gender)
VALUES (:fb_id, :firstname, :lastname, :email, :gender)");
$stmt->bindParam(':fb_id', $userid);
$stmt->bindParam(':firstname', $userfirst_name);
$stmt->bindParam(':lastname', $userlast_name);
$stmt->bindParam(':email', $useremail);
$stmt->bindParam(':gender', $usergender);
// insert a row
$userid = $_POST['userid'];
$userfirst_name = $_POST['userfirst_name'];
$userlast_name = $_POST['userlast_name'];
$useremail = $_POST['useremail'];
$usergender = $_POST['usergender'];
$stmt->execute();
// prepare sql and bind parameters for 2nd insert
$stmt = $conn->prepare("INSERT INTO orders (fb_id, cb, gb, invite)
VALUES (:fb_id, :cb, :gb, :invite)");
$stmt->bindParam(':fb_id', $userid);
$stmt->bindParam(':cb', $cb);
$stmt->bindParam(':gb', $gb);
$stmt->bindParam(':invite', $inviteo);
// insert a row
$userid = $_POST['userid'];
$cb = "1";
$gb = "10";
$inviteo = "0";
$stmt->execute();
echo "1";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Once the insert statements are completed I send an echo back to the Javascript function, and then a Javascript alert appears on screen to tell me if the insert was successful or not. This works perfectly in Chrome, but I don’t get any alert with the other three browsers, and nothing gets entered into the database when I try to use them. The fact that there’s no alert telling me it’s not successful makes me think that the error is in the Javascript not working with the browsers, but then again, it was working perfectly on all browsers before I switched the PHP to PDO.
I've made sure that Javascript is enabled, pop-ups aren't blocked, and I've tried looking at the console in Firefox but I don't see what could be wrong.
Any help or advice on this would be great. Thank you in advance!
I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});