Triggering jquery ajax mysql insert using a gamepad - php

This little project of mine involves registering actions associated with buttons pressed on a gamepad (PS3 style for the record). Because html5 supports gamepads I decided to use it as a fast and simple way for development.
The thing is, when running the ajax and the call of the php script, after pressing a button, the insert statement is duplicated. This not happens when I set async: false and use Firefox, but this goes against the purpose of ajax, and from what I've read, not an elegant thing to do.
This is what I have in my index.html (borrowed from here https://gamedevelopment.tutsplus.com/tutorials/using-the-html5-gamepad-api-to-add-controller-support-to-browser-games--cms-21345)
function reportOnGamepad() {
var gp = navigator.getGamepads()[0];
var html = "";
html += "id: "+gp.id+"<br/>";
html += "timestamp: "+gp.timestamp+"<br/>";
html += "<br/>move<br/>"
if (gp.buttons[0].pressed) { var moves=" B1"; $.ajax({
url:'my.php',
method:'POST',
data:{
moves: moves
},
}); html+= " <br/>";
};
and my my.php
$conn = new mysqli($servername, $username, $password, $dbname);
$moves = $_POST['moves'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO test (moves) VALUES ('$moves')";
$conn->query($sql);
$conn->close();
Simple stuff as you can see. My knowledge of jquery/javascript is very basic so, if someone with more experience could point me what I'm doing wrong, I would really appreciate it. Thank you.

The tuts+ tutorial you linked has some code to set up a polling interval for Chrome as a workaround for unreliability in the gamepadconnected event:
//setup an interval for Chrome
var checkGP = window.setInterval(function() {
console.log('checkGP');
if(navigator.getGamepads()[0]) {
if(!hasGP) $(window).trigger("gamepadconnected");
window.clearInterval(checkGP);
}
}, 500);
This bug is fixed in the latest version of Chrome and the workaround could be causing your issue. For instance, if checkGP fires before the gamepadconnected event is received, you may register the reportOnGamepad interval twice.

Related

PHP how to connect two players

I'm making a website. and one of the features i want it to have is to have a simple game that connects 2 players together. my problem is I don't know how to make it so both player are in the same "room" because on room holds only 2 players.
On way i approached this is once one player joined, he gets a "wait for next player" message and waits while sending to the database that one player have joined. how do i make it keep checking for the next 3 minutes if the next player joined?
UPDATE
First here is the code so far:
<html>
<title>SiteName (test)</title>
<head>
<?php
$servername = "localhost";
$u
sername =
$password =
$dbname =
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);
$stmt = $conn->prepare('SELECT * FROM game');
$stmt->execute(array('gameID' => $gameID));
while($row = $stmt->fetch()) {
print_r($row);
echo "<br />\n";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
<button onclick="myFunction()" id="w">Look for Game</button><br>
<script>
function myFunction() {
var elem = document.getElementById("w").innerHTML = "Wait";
var counter = 10;
var label= document.getElementById("lbl");
var counter = 10;
var clabel= document.createElement("p");
clabel.innerHTML = "You can download the file in 10 seconds.";
var id;
label.parentNode.replaceChild(clabel, label);
id = setInterval(function() {
counter--;
if(counter < 0) {
clabel.parentNode.replaceChild(label, clabel);
clearInterval(id);
} else {
clabel.innerHTML = "You can download the file in " + counter.toString() + " seconds.";
}
}, 1000);
}
</script>
<?php
$conn = null;
?>
</body>
</html>
Am trying to make it so that if the first player joined, he will be waiting (i have it for 10 seconds here as a test) until the other joins. the way am trying to do it is to have a field in the database will know if the a player is in that page and await the next player. I read something about long polling but not sure how to implement it for my case.
Any feed back would be helpful, Thank you
PHP is not the best language to do this in, but if you still want to do it.
Look into using Ratchet (http://socketo.me/), which is a PHP websocket library. A websocket is full duplex, meaning that a connection between the server and client is kept open. Game state and player actions can then be communicated through this.
http://socketo.me/docs/hello-world is an example you can learn from.
first you will want javascript or some client side code to handle this. as php will execute on the server side then display to the user. if you use ajax with javascript you can get the client side and server side to work together.
you will want to use a while loop, in this loop you will set a timeout.
in the while loop you can call the ajax script you want untill you get your result you want. I'm assuming you plan on making this a turn by turn game for the players. you will want a table that sets "true" to if player 1 or player 2 are in the game. if both are turn then the game begins.
Hope this logic helps

MySQL update query using AJAX and PHP

Scenario: I'm trying to incorporate it so that when you click this button, it adds 1 to a value in the database.
I've read so many articles about AJAX today but no solution.
P.S. The query works fine directly from the command line.
This is what I've written so far but I think I'm completely missing something.
game.php
<script>
function logCountAdd(){
var request = $.ajax({
type: "GET",
url: "logCountAdd.php"
});
request.done(function(msg ) {
alert('Success');
return;
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
};
</script>
</head>
<body>
<button type="button" onclick="logCountAdd()">Gather Resources</button>
logCountAdd.php
<?php
$connection = mysqli_connect("localhost","root","","users");
if (mysqli_connect_errno())
{
echo 'NOT_OK';
}
mysqli_query($connection, "UPDATE uc_users
SET logCount = logCount + 1
WHERE user_name='Gregory'";)
mysqli_close($connection);
echo 'OK';
?>
Problem: After I click the button, the value in the database does not change.
The Error Code: GET logCountAdd.php 500 (Internal Server Error)jquery-1.11.2.min.js:4 m.ajaxTransport.sendjquery-1.11.2.min.js:4 m.extend.ajaxgame.php:7 logCountAddgame.php:22 onclick
First question asked on here, sorry guys!
mysqli_query($connection, "UPDATE uc_users
SET logCount = logCount + 1
WHERE user_name='Gregory'";)
^ misplaced semicolon
move it to after the close parenthesis. You may want to turn on error reporting to make debugging easier
error_reporting(E_ALL);
ini_set('display_errors','On');

PDO Ajax updating mysql database

I need help in this PHP Ajax updating mysql database using PDO. I wanted to update the database if a user checks the checkbox. Below is my code:
JS:
$('input[name=product_new]').click(function(){
var chkbox_id = $(this).attr('alt');
var chkbox_selected = $(this).is(':checked');
if(chkbox_selected == true)
{
chkbox_selected = "checked";
}
else
{
chkbox_selected = "uncheck";
}
$.post({
url: "../products_listing.php",
type: "POST",
data: {product_id: chkbox_id, product_new: chkbox_selected},
cache: false,
success: function(){}
});
});
PHP page with PDO to update database:
$id = $_POST['product_id'];
$product_new = $_POST['product_new'];
if(isset($_POST['product_new']))
{
try
{
$query = "UPDATE productinfo SET new_arrival=? WHERE id=?";
$stmt_new_chkbox = $conn->prepare($query);
$stmt_new_chkbox->bindParam(1, $product_new, PDO::PARAM_STR);
$stmt_new_chkbox->bindParam(2, $id, PDO::PARAM_INT);
$stmt_new_chkbox->execute();
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
}
It was working when I use mysql but now I've changed it to use PDO, it won't work anymore. I can't find where went wrong. Thanks in advance guys.
Below is the old code from mysql_:
$id = mysql_real_escape_string($_POST['product_id']);
$product_new = mysql_real_escape_string($_POST['product_new']);
if(isset($_POST['product_new']))
{
$upt_new=mysql_query("update products_list set new_arrival='$product_new' where id='$id'");
}
Ok! I know what's wrong already. The damn directory path. I took out ../ and it works! Kinda weird though.
Because my js file is in JS folder and products_listing.php is outside of the js folder. Isn't it supposed to be ../products_listing.php?
Can anyone tell me why it's not working which it is supposed to be?
Thanks in advance guys!
Just split your task into 2 parts: AJAX part and PDO part.
First of all make sure that your PDO part works well. Make a mock $_POST array, and then start playing with PDO calling this script directly, without AJAX. Ask questions here, if something goes wrong. then, as you ret it to work, move to AJAX part, the same way - first, without PDO by just by sending data to server and verifying if it's correct.
Solving 2 problems at once makes things a lot harder. Always split your task into separate parts and solve them one by one.

Get Data from Mysql on init

I need to get data (image_url, names, etc) from mysql when the page is open.
I'm thinking to do this on oninit() event. However I'm not sure if this is the best approach.
The code I got so far is taking more time than I was expecting so maybe I'll need to add a "loading" message while this operation is going. Am I in the right way?
Thanks in advance
Okay, there are scenarios here -- and I'm not too sure about what you need. The first is pulling the data once on page load. You present your data through a view using a controller to access your data model. Everything is processed on page load and is static.
// Use simple PHP
<?php
$con = mysql_connect("localhost","peter","abc123");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($result))
{
echo $row['image'];
echo $row['names'];
// etc.
}
?>
The second is more dynamic, using AJAX to pull data from your server continuously. You can use JavaScript's setInterval to load data over a regular period:
// Load MySQL data every 15 seconds with jQuery
$(function () {
setInterval(function() {
$.ajax({
url: '/path/to/controller',
data: 'var1=hey&var2=bro',
dataType: 'html',
type: 'POST',
success: function(data) {
$('.div_of_your_choice').html(data);
})
});
},15000);
});

resetting variables in php to display in javascript

I'm trying to get some values off a DB and then putting those values into javascript variables. I managed to do just that, the problem I'm having is when the values in the DB change the values of the variables don't. I figured the problem lies within my PHP, but I cant find it. Can you guys help me?
here's my code:
PHP
<?php
session_start();
if(!isset($_SESSION['u_name'])){
$_SESSION['u_name'] = '';
}
mysql_connect ("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db('raffleiz_Main')or die ("cannot select DB :(");
$signups = mysql_query("SELECT * FROM `Rafflez_info`") or die ('Error: ' . mysql_error());
$row = mysql_num_rows($signups);
//pull all of the data and store it
for($p = 0; $p < $row; $p++){
$participants[$p] = mysql_result($signups, $p, "#_participants");
};
for($a = 0; $a < $row; $a++){
$max_participants[$a] = mysql_result($signups, $a, "max_participants");
};
?>
and my javascript function:
function progress(){
var signups = "<?php echo $participants[0]; ?>";
var maxP = "<?php echo $max_participants[0]; ?>";
alert (signups);
alert (maxP);
var pSignup = signups / maxP;
alert (pSignup);
var total = 550 * pSignup;
var theImg = document.getElementById('progress');
theImg.width = total;
alert (total);
};
I put the "alert" command there so that I could see the change in the values. right now the values don't change no matter what I change them to in the DB.
PHP is a server-side language, meaning that when it served the script from the server to the client, there is no going back.
JavaScript is a client-side language, thus can receive values from a server-side language such as PHP. The values received are then client-side only, a copy if you will.
You can use the XMLHttpRequest API to request a script from a server, updating the local client-side values.
I recommend using the jQuery $.ajax function to easily achieve that.
Here's a nice tutorial from Nettuts to get your started.
You need to call your php page and ask it if values are changes. You can easily use jQuery AJAX to achieve that. Use JSON for easier data transfer. If you want to check if values are changes every 3 seconds for example you can do this:
var interval = window.setInterval(function(){
jQuery.ajax({
url: 'your php file address',
success: function(data){
progress(data)
}
});
}, 3000);
You will need to change you proccess and php code. This is just to give you the idea.

Categories