Javascript game info to PHP - javascript

So after the player loses I want their score to be updated into the database using PHP.
I have a separate javascript class that actually runs the entire game but it uses setInterval to check the index.php function to check if the player lost; if they do they I want it to update the database. The update works but its not taking the score and is just replacing whatever highscore they had with 0.. obviously not what I want. I know people are going to recommend AJAX but my professor only wants PHP and Javascript so I'm getting really confused here... heres the function inside the index.php
<script type="text/javascript">
function checkFinished(){
if(end()){
<?php
if(isset($_SESSION["id"])){
$id = $_SESSION["id"];
$userName = $id["name"];
$update = "UPDATE bloodred SET score='?>score<?php' WHERE name='$userName'";
$update = $dbh->prepare($update);
$update->execute();
}
?>
gameover = false;
}
}
</script>
as you can see im trying to grab the javascript variable score by doing this in the $update variable
score='?>score<?php'
does anyone know any quick short cuts to do this? thanks !

Javascript is client side, and PHP is server side. When you remove the PHP from your javascript, you end up with this:
<script type="text/javascript">
function checkFinished(){
if(end()){
score
gameover = false;
}
}
</script>
If you would like to update the database with the content of a JavaScript variable, you will need to make a new request to the server. This can be a redirect, AJAX, socket, etc. But putting PHP inside of your javascript expecting it to execute like this just doesn't work.
Just a side note, this will work the other way around since PHP is executed first. This does not help your question, but might help clarify why your code isn't working:
This will work:
<script>
alert("<?php echo $variable; ?>");
</script>

After reviewing everything you all said to me I was able to think of a simple solution:
Heres the new javascript:
<script type="text/javascript">
function checkFinished(){
if(end()){
document.getElementById("setScore").value = score;
gameover = false;
}
}
</script>
added a simple form:
<form name="highscore" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<input id="setScore" name="setScore" value="" type="submit" />
</form>
then some php
<?
if(isset($_POST)){
if(isset($_SESSION["id"])){
$id = $_SESSION["id"];
$score = $_POST["setScore"];
$userName = $id["name"];
$update = "UPDATE bloodred SET score='$score' WHERE name='$userName'";
$update = $dbh->prepare($update);
$update->execute();
}
}
?>
Thought id post this in case anyone else needed it. Thanks again guys for your help!

Without using ajax you can create an iframe and post to it using a form on the page with the target attribute.
javascript
function checkFinished(){
if(end()){
var iframe = document.getElementById('updateScore'),
form = document.createElement('form'),
input = document.createElement('input');
if(!iframe){
iframe = document.createElement('iframe');
iframe.name = 'updateScore';
iframe.id = 'updateScore';
}
input.name = 'score';
input.value = getGameScore();
form.action = '/updatescore.php';
form.method = 'post';
form.target = 'updateScore';
form.appendChild(input);
form.submit();
form.remove();
gameover = false;
}
}
updatescore.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['id']) && isset($_POST['score'])){
$id = $_SESSION["id"];
$score = $dbh->real_escape_string($_POST['score']);
$userName = $id["name"];
$update = "UPDATE bloodred SET score='$score' WHERE name='$userName'";
$update = $dbh->prepare($update);
$update->execute();
}
?>

First of all: AJAX is Javascript.
Second: PHP is a Server-Side language. Javascript a Client-Side. So what you want mixing PHP code with JS code will never work. When JS execute, all PHP code was already evaluated and executed by PHP compiler.
To solve your problem there are some methods,like:
You could use HTML5 WebSocket, but this is kind of AJAX and the user must have a updated, newer, browser and you must implement de server side of PHP socket to listen the user gameover event (too much resources of the server).
You could use AJAX (since AJAX is Javascript), is the fast, easy and recomended.
You could redirect the user, when the game over, to another page (or the same, this is your logic) passing a querystring or a cookie with the new score, doing this the PHP code can take the updated and correct value of score and update the database.
Just remember that all forms listed above are insecure because run in client-side and so, any client (AKA user/player) can change the value of score for whatever he wants.
If you cannot use AJAX (again, AJAX is Javascript), if you cannot use WebSockets (Server limitation or HTML 5 limitation), you could load a PHP through a script tag or a iframe tag (but don't tell anybody that was me who told you do that haha)
<script type="text/javascript">
var score = getCurrentScore(); //a simple method that returns the current user score to be stored in database
function updateScore()
{
var s = document.createElement("script"); // create a tag script via JS
s.scr = "updateScore.php?score=" + score + "&nocache=" + Math.floor((Math.random()*1024)+1); // determine that source of this script is the url of script that updates the score for current user, with the queryString score value. nocache querystring with random value between 1 and 1024 is just to guarantee that the script will be loaded every time and not a cached version of a file will be acessed. For better results add a HTTP header "expire" in the updateScore.php with a small or negative value.
s.type= "text/javascript"; // type of script (make sure that updateScore.php response a content-type text/javascript e a valid or empty javascript code
document.getElementsByTagName("head")[0].appendChild(s); //append the tag script at the end of tag head of the current page
}
// call updateScore() method when user gameover!
</script>
When you call the method updateScore it will produce something like:
<script type="text/javascript" src="updateScore.php?score=1000&nocache=123"></script>
This is similar a AJAX request, or a direct request or direct access to the file. Where score=1000 represents a score with value 1000 and nocache=123 is a random value just to guarantee the fresh load of file. (calling method again, nocache value /probably/ will change to something different than 123...)

Related

PHP, Javascript, mysql, and selection lists

I'm working on a piece of some software that will grab information from a mysql database and throw it onto our form dynamically. I'm running into a couple problems, though. I'll give a quick rundown of some functionality.
When the form loads, we have a ton of selection lists. These are all populated through arrays with various keys/values in php. When I select an option from one list, we'll call it a "customers" list, on-click I need to check if that customer has a special flag (stored in the database), and update another selection list based on that data.
How I understand the core of my solution is I need to have a javascript trigger on-click, which I have. The function that is called references a php page that handles the database query through a class and it's function.
<script>
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer='+customer);
}
</script>
This function then talks to my php. The CustomerProvider class works 100%. I have tested that thoroughly on other pages. The problem arises when I try to actually get my selection list to change.
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != '')
{ ?> <script>var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';</script> <? }
else return;
}
?>
I'm coding in javascript literally for the first time ever and they kinda just threw me on this project. I know that my portion isn't being read as html or output as I intend. I know that every other part of the php and the first bit of javascript seems to be executing okay. Any help would be incredibly appreciated.
You seem to be on the right track but just for your own sanity here are a couple pointers. You shouldn't be returning Javascript from PHP for a situation like this. Instead you should be relying on Javascript promises to wait for a response containing just the data and continue the execution of your client code once you have your values returned. Take a look at this:
<script>
function setService() { // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer=' + customer, function(data) {
console.log(data + ' was returned from your php script!');
if(data.hasContract=='1')
$('#ticket_service').val('Contracted Hours');
else
$('#ticket_service').val('No Contracted Hours');
});
}
</script>
And then your PHP script will just look like this:
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){
$hasContract = 1;
}
else
$hasContract = 0;
echo json_encode(array('hasContract' => $hasContract));
}
?>
Therefore returning only the data needed for the client app to continue... not application logic
Your code isn't doing anything with the output of the PHP script. If you want the output to be inserted somewhere in the DOM, you should use .load() rather than $.get.
$("#someelement").load('thePage.php?key=setService?customer='+customer);
This will put the output into <div id="someelement">. If the output contains <script>, the script will be executed.
If you know the result is just a script, you could use $.getScript() instead of $.get. Then the output should just be the Javascript, not enclosed in HTML tags like <script>.
The problem here is that you are not using the result from the server. Your JavaScript may indeed be correct, but the browser never sees or runs it. From the docs:
Request the test.php page, but ignore the return results.
$.get( "test.php" );
Try this code, which utilizes the $.getJSON() shortcut function. I've written two versions, which you can see commented in the code. One moves the logic for determining contract status into the JS. Either should work.
PHP
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
// Default output
$output = array('hasContract' => false);
// Customer has contract
if ($s != '')
$output['hasContract'] = true;
echo json_encode($output)
// Alternative: PHP just returns getHasContract, JS determines action
// (this would replace $ouput, conditional, and echo)
// echo json_encode(array("hasContract" => $s));
}
?>
JavaScript
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.getJSON('thePage.php?key=setService?customer='+customer, function(result) {
// Alternative
// if (result.hasContract != "")
if (result.hasContract)
{
var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';
}
});
}
As others wrote, your code doesn't do a thing with the GET variables.
the element "ticket_service" doesn't exists on page and even if it was, the code has no impact on the page that sent the request, you should print/echo the result you want to display/return and then manipulate it with JS/Jquery.
since I'm against GET and pro POST which is safer method, here's an example with POST:
JS:
function postSomthing(customerID){
$.post(
'thePage.php',
{key:'setService',customer:customerID},
function(data){
if(data!='x'){
$('#ticket_service').val(data)
}
else{alert('no ticket');/*whatever you want to do*/}
});
}
PHP(thePage.php) :
if(isset($_POST['key']) && $_POST['key'] == 'setService'){
$customer = intval($_POST['customer']);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){echo 'x';/* false, or whatever you want*/}
else{echo 'Contracted Hours';}
}
notes:
you should create an element with the id "ticket_service" in the viewed page and not in the backstage one.

How to pass javaScript values to PHP

How to pass javaScript values to PHP, my code is following
<script>
function a{
var b = a;
}
</script>
<button onclick="a(2)">Values</button>
<?php
$select = mysql_query("select * from tabl1 where id='values'"); // values comes here
echo $select;
?>
There's a lot of thing you could do.
Principal things you have to know is that javaScript run on the client side (browser), while PHP is running on the server.
Then If you want to pass a variable from your JS to your PHP you have to make a server call.
There's various way you can use in order to send variable from client to server.
As I understand from your example, it looks like your php code and your javascript on the same file. so maybe call your file another time will be enough for you.
Let's say your file's name is index.php.
<script>
function yourJavascriptFunction(id) {
window.location.href = "index.php?id=" + id;
}
</script>
Then in change your PHP code to this:
<?php
$select = mysql_query("select * from tabl1 where id='".$_GET['id']."'"); // values comes here
echo $select;
?>
$_GET will get the variable you've sent in your Js function.
Doing like this will refresh the page.
May be you don't want to refresh the page? Then look at the ajax way.
I hope it helps you

How to read a session variable from a php file in JavaScript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
There have been far too many questions on this subject but I still fail to understand.
Case:
Hyperlinked image
OnClick of image: Check if session exists
If session exist, open link
If session does not exist, show login form
onclick is calling a JavaScript function:
var my_global_link = '';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
// .. then show login modal that uses 'js/whitepaper-login.js'
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
Global variable is being saved in another php file as :
$_SESSION['logged_in'] = 1;
I am unable to capture the session value in the var check. Can you advise?
Using jQuery here is a simple example of how to get a PHP $_SESSION into your JavaScript:
session.php
<?php
session_start();
$_SESSION['foo'] = 'foo';
echo $_SESSION['foo']; // this will be echoed when the AJAX request comes in
?>
get_session.html (assumes jQuery has been included)
<script>
$(function() {
$('a').click(function(event){ // use instead of onclick()
event.preventDefault(); // prevents the default click action
// we don't need complex AJAX because we're just getting some data
$.get('session.php', function(sessionData) {
console.log( sessionData ); // session data will be 'foo'
});
});
});
</script>
click
If this is successful you'll see the data and can use it in other JavaScript functions by passing the data appropriately. I often find it handy to json_encode() session data, returning JSON to be used by JavaScript, but there is no need to in a simple example such as this one.
Make the request to someone file.php
$( document ).ready(function(){//run when DOM is loaded
$.post("file.php", //make request method POST to file.php
function(data){ //callback of request is data
var arr = jQuery.parseJSON(data); //make json decoding
if(arr.logged == 1) //arr.logged is value needs
#do
})
})
file.php
<?php
session_start(); //start session for my dear friend Jay Blanchard
$_SESSION['logged_id'] = 1; //init value for example
$array = array('logged' => $_SESSION['logged_id']);//creat array for encoding
echo json_encode($array); //make json encoding for call back
?>
your javascript is not a very good solution, as it can be hacked easily. One can simply change the value of check to whatever one likes, and even without a login one would be able to access the link of the picture.
A better implementation would probably be something like:
<img src="img.png" alt="" />
checklogin.php would then verify the $_SESSION variable. If validated, you can use header("Location: something.html"); to redirect to where you want to bring the user. If not logged in, you can instead redirect to the login page: header("Location: login.php");
#Sarah
You have to first call the php file via ajax and set the javascript variable as the result. Since the javascript is a client side scripting language hence it can't read server side PHP script.
Hence on click call javascript function
function someFunc(){
//Fire Ajax request
//Set check variable
//and perform the function you want to ...
}
<?php include "sess.php"; ?>
<script type="text/javascript">
var my_global_link = 'testr.com';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
</script>
<a href="#" onclick="show_login('test')" >test</a>
file1.php
<?php
session_start();
$_SESSION["logged_in"] = 1;
?>
sess.php
I have done this using two files. You may have not included session file I guess. Its working fine for me.

How to transfer a value on DB to JAVASCRIPT through PHP

<?php
// Connect to database server
mysql_connect("192.168.1.101/phpmyadmin/", "root", "praticas") or die (mysql_error ());
// Select database
mysql_select_db("logs_history") or die(mysql_error());
//---> at this point, I want yo pull a VALUE from a column called potencia_ativa and insert in
// the code JS below
mysql_query($strSQL);
// Close the database connection
mysql_close();
?>
//JS code-------------------------------------------------------------------------------------------
<div id="graphHolder" style="height:75%;width:100%"></div>
<script type="text/javascript">
setInterval(
function() {
var d1 = [];
for (var i = 0; i < parseInt(document.getElementById('number').value,10); i += 0.5) {
d1.push([ //----------> pull the value from the php/DB as a FLOAT
]);
}
$.plot("#graphHolder", [{
label: "Label",
data: d1,
lines: { show: true, fill: true }
}
]);
}, 1000);
</script>
Remember, PHP executes on the server and GENERATES the page that runs the Javascript on the client. Putting a value from PHP into the JS code is as simple as:
<script>
var foo = <?php echo json_encode('bar'); ?>;
</script>
If you need to send the PHP data over AFTER the page was generated and already send to the client, then you need to have the client execute an AJAX request to fetch that data from the server. Once PHP has shoved the page out the door, it's basically done and can't "reach out" to the client to do updates on its own.
Also: Note the use of json_encode(). You should NEVER dump output from PHP directly into a Javascript context without it. Anything else puts you at risk of generating JS syntax errors, which will kill the entire JS code block.
Why are you using Interval? Are you trying to update the displaying page data/value automatically after some time passed? That won't work, because if anything changes in database, It won't change in the displaying page, unless you use AJAX to call your php script and return some values, and then, change in the displaying page.
To get a value from PHP script to JAVASCRIPT, you just need to use the php clausule;
var test = <?php echo $variable; ?>
// echo for strings, ints, floats.
// print_r for arrays.
Of course, if your PHP script already injected the data into the page/the data is in the same page you're using JAVASCRIPT, assuming that you have already fetched the data, handled it and etc.

PHP inside Javascript in a registration form (for validation)

I'm developing a registration form for my site. Actually when a visitor choose an username, a php query to my MySQL DB is used to control if it's already used and if so, a javascript windowd appear.
Can i use a PHP query inside Javascript for displaing a real-time notice near the form (using HTML5)?
<script>
var username = document.getElementById('username');
var userdb = <? php control_username($username); ?>
var checkUsername = function () {
if (userdb.value == true) {
username.setCustomValidity('Username already used');
} else {
username.setCustomValidity('');
}
};
username.addEventListener('change', checkUsername, false);
</script>
and here there's the php function:
<?php function control_username($username){
$db=connessione_db();
$query = "SELECT username FROM utente WHERE username = '$username';";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[0]==$username){
return TRUE;
}
else{
return FALSE;
}
$query=NULL;
}
how can i do?
You can use AJAX or jQuery AJAX to send a request to a php page, Check if the username exists, return the result, and display it using Javascript again.
Here is the jQuery sample:
<script>
$.ajax({
type: 'POST',
url : 'checkUsername.php',
data: {'username' : $('#username').html()},
cache : false,
success: function(data){
if(data == 'exists')
//username exists
alert('username already exists!');
},
error: function(request , status , error){
alert(request.resposeText);
}
});
</script>
and this should be your checkUsername.php file:
<?php
$db=connessione_db();
$query = "SELECT count(*) as count FROM utente WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[count] > 0)
echo 'exists';
else
echo '';
PHP is run on the server, Javascript is run on the client's machine. Once your PHP script has generated a page and sent it to the user, it doesn't run any longer. Your client has no knowledge of a PHP script. It can't directly run, call, or read anything about your PHP script because it resides solely on the server (never on the client's machine). Your client's machine does, however, know about your Javscript since it has been sent along with the page. If you want to access PHP functionality from your page, you can either send a GET/POST call to the server and reload the page, or use AJAX to make the call in the background. Check out Jquery's implementation of AJAX calls, it makes using it pretty simple.
No you can't do it like that. PHP is serverside, Javascript clientside. The moment Javascript is executed is the code working clientside. All PHP code is fixed.
Compare it to the combination of HTML and PHP in an HTML page. It is fixed there as well. Same applies to PHP in Javascript.
Here are some answers from related questions on stackoverflow:
How to put php inside javascript?
How to embed php in javascript?
Here is an example from ajaxref, showing the basics:
http://ajaxref.com/ch3/asyncsend.html
This is another tutorial showing how an ajax call is handled:
http://code.tutsplus.com/articles/how-to-make-ajax-requests-with-raw-javascript--net-4855
I advice you to first understand this process and later on start using a framework like jQuery.

Categories

Resources