I'm trying to make a snake game within my website, and have been running into the issue of not being able to send score and user data (for a leaderboard) to my SQL database. I'm really new to web dev, so I'm not sure if maybe there's a super simple fix I just keep overlooking. Here's the part of the game's JavaScript code block that I am focusing on:
// snake occupies same space as a body part. reset game
if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
//Ask for new user if one isn't registered
if (document.getElementById("userV").innerHTML == "User: ____")
{
document.getElementById("userData").innerHTML = window. prompt("User:");
document.getElementById("userVisible").innerHTML = "User: " +
document.getElementById("userData").innerHTML;
}
/*
*Here is where I need to send user and score data to snake_scores table
*/
snake.x = 160;
snake.y = 160;
snake.cells = [];
snake.maxCells = 4;
snake.dx = grid;
snake.dy = 0;
snake.score = 0;
document.getElementById("scoreData").innerHTML = snake.score;
document.getElementById("scoreVisible").innerHTML = "Score: " + snake.score;
apple.x = getRandomInt(0, 25) * grid;
apple.y = getRandomInt(0, 25) * grid;
}
So overall, my issue is that I can't figure out how to send these JS values through PHP and to my SQL server.
I'll make some assumptions about the game page itself, given that you probably don't want the page to refresh during play a good solution would be Ajax (Asynchronous JavaScript And XML). Essentially this is making a post request in the background to your server without reloading the page.
I find jQuery pretty easy to use:
https://api.jquery.com/jQuery.post/
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So using Ajax to post to a url that is expecting the information to then update server side you would access this in php using something similar to the following.
$leaderboard = $_POST['leaderboard']
Hope this points you in the right direction at least. Good luck on the game.
Related
I am using an 'infinite scroll' script that keeps sending requests to the database even when there are no more records. When that happens, it reloads the last set on the page. I would like for the function to stop running when it reaches the last record on the database. I'm new to JS so this is a bit difficult for me to troubleshoot, also, I'm not using jQuery. I am doing most of the work in the PHP script.
I've been reading a lot of posts in here about 'infinite scroll' and I am unable to get how other people check the limits in JS.
JavaScript
function loadPosts(){
var target = document.getElementById('PostsContainer');
var contentHeight = target.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
var xhr = ajaxObj("POST", "loadContent.php");
xhr.onload = function(){
target.innerHTML += xhr.responseText;
}
xhr.send("action=loadMore");
}
}
window.onscroll = loadPosts;
PHP
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC LIMIT 2" //Original content on page
$totalPosts = 12; (query to DB)
$max = 1;
$current = 2; //Start on record after initial content
while($current < $totalPosts){
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC
LIMIT $current, $max";
$result = $db_link->query($sql);
$posts_list += ... //Collect the data from DB
$current++;
}
echo $posts_list;
No matter how many times I keep scrolling the new content keeps loading even after I run out of records in the DB. Output keeps repeating every single time I get to the bottom of the page. In this case I have 7 posts in the DB I start with 7, 6... then I keep getting posts 5-1.
So in this case what you can do,
just add one parameter in json, from php or server side which will tell, is data present or not, based on that, you can stop calling loadPosts function
so basically Algorithm be like,
...php
while($current < $totalPosts){
......................
......................
if($current >= $totalPosts)
{
$getNext = False;
}
else
{
$getNext = True;
}
}
...javasrcipt
function loadPosts(){
if(!getNext)
return false;
else
{
......................
......................
}
}
window.onscroll = loadPosts;
Hope this strategy will help you
Battlefield Page
In the image above, there is a page that has a battlefield with 20 users on it. I have written JavaScript to capture the data and store it in a MySQL db. The problem comes into the picture when I need to hit next to go to the next page and gather that data.
It fetches the next 20 users with an Ajax call. Obviously when this happens, the script can't log the new information because the page never loads on an Ajax call which means the script doesn't execute. Is there a way to force a page load when the Ajax link is clicked?
Here's the code:
grabData();
var nav = document.getElementsByClassName('nav')[0].getElementsByTagName('td')[2].getElementsByTagName('a')[0];
nav.addEventListener("click", function(){
grabData();
});
function grabData(){
var rows = document.getElementsByClassName('table_lines battlefield')[0].rows;
var sendData = '';
for(i=1; i < rows.length -1 ; i++){
var getSid = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].getElementsByTagName('a')[0].href;
var statsID = getSid.substr(getSid.indexOf("=") + 1); //Grabs ID out of stats link
var name = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].textContent.replace(/\,/g,"");
var tff = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[3].textContent.replace(/\,/g,"");
var rank = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[6].textContent.replace(/\,/g,"");
var alliance = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[1].textContent.trim();
var gold = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[5].textContent.replace(/\,/g,"");
if(alliance == ''){
alliance = 'None';
}
if(gold == '??? Gold'){
gold = 0;
}else{
gold = gold.replace(/[^\/\d]/g,'');
}
sendData += statsID + "=" + name + "=" + tff + "=" + rank + "=" + alliance + "=" + gold + "#";
}
$.ajax({
// you can use post and get:
type: "POST",
// your url
url: "url",
// your arguments
data: {sendData : sendData},
// callback for a server message:
success: function( msg ){
//alert(msg);
},
// callback for a server error message or a ajax error
error: function( msg )
{
alert( "Data was not saved: " + msg );
}
});
}
So as stated, this grabs the info and sends to the php file on the backend. So when I hit next on the battlefield page, I need to be able to execute this script again.
UPDATE : Problem Solved. I was able to do this by drilling down in the DOM tree until I hit the "next" anchor tag. I simply added an event listener for whenever it was clicked and had it re execute the JavaScript.
Yes, you can force a page load thus:
window.location.reload(true);
However, what the point of AJAX is to not reload the page, so often you must write javascript code that duplicates the server-side code that builds your page initially.
However, if the page-load-code-under-discussion runs in javascript on page load, then you can turn it into a function and re-call that function in the AJAX success function.
Reference:
How can I refresh a page with jQuery?
I have a php/mysql auction site which uses a while/break loop to check on the current active item in a items table using ajax polling. It breaks if there is a new bid or a new lot. The server script is:
if ($action == "ping"){
$idle_lot = $_POST['lot'];
$idle_bid = $_POST['bid'];
$timeout = 15;
$now = time();
while((time() - $now) < $timeout) {
$get_bid_status = $db->prepare("SELECT current_bid, lot_number FROM ".$lots_table." WHERE lot_status='active' LIMIT 1");
$get_bid_status->execute(array());
$existCount = $get_bid_status->rowCount();
if ($existCount > 0 ) {
while($row = $get_bid_status->fetch()) {
$current_bid = $row["current_bid"];
$lot_number = $row["lot_number"];
}
if (($current_bid != $idle_bid)||($idle_lot != $lot_number)) break;
sleep(1);
} else {
$return_array[99] = "closed";
}
if ($existCount == 0 ) break;
}
//other php code here
}
The client side is a simple AJAX function:
function waitForMsg(lot, bid){
$.ajax({
type: "POST",
url: "live_bidding_script.php",
data: { action: "ping", lot: lot, bid: bid},
dataType: "json",
async: true,
cache: false,
timeout:50000,
success: function(data){
//other jquery code here
setTimeout(function(){waitForMsg(lot, bid)}, 1000);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//other jquery code here
setTimeout(function(){waitForMsg(lot, bid)}, 1000);
}
});};
The script was working very well in testing, but when we had a simulated auction, we suddenly crashed and burned. We got the dreaded:
SQLSTATE[42000] [1226] User 'XXXX' has exceeded the 'max_user_connections' resource (current value: 20)
I removed the loop, which seemed to be the major cause of the problem, (ie kept the connection open for 15secs at a time, and quickly used up all the 20 connections) and reverted back to simple polling.
Now from reading dozens of articles, polling and even long polling is not the 'way to go' so to speak. So I am about to recode the site.
My question is out of the newest technologies which use websockets (ie: pub nub, node.js, socket.io or even Comet) would they get around this issue of 'max_server_connections', and if so please explain how/why.
I understand the newer technologies work differently but they all seem to have a fallback approach (usually polling) if WS protocols are not available, which leads me to believe if we had 1000 concurrent users and 20+ had older browsers for example, we would still get the same 'max_server_connections' issue.
PS: we are on a prepaid hosted server for the next few years and simply increasing the number of 'max_user_connections' is a no go. Changing hosts may be an option, albeit a very expensive/time consuming exercise.
Thanks.
I have implemented an online quiz using jQuery. I have this specific requirement I want to implement at the end of the quiz.
if (number_of_answered_questions == total_questions) {
save the score to the database;
redirect to redirect_url;
}
This redirect_url depends on the score. (for ex: if the score < 10, redirect to page1.html and if 10 < score < 15, redirect to page2.html)
I tried using jQuery.post, but I'm not sure how to implement both in the same 'post'.
How can I implement these two tasks in jQuery?
I can't write the logic to "save to database" in the redirect pages because they keep changing. (I mean admin can change the redirect pages).
You can trigger a redirect in JS by modifiying window.location.href. You simply need to change your pseudocode/conditionals into the JS equivalent, and then modify the href accordingly to redirect, once your save completes successfully (i.e. in the callback for the post method).
var total_questions = ...;
var number_of_answered_questions = ...;
var score = ...;
// other quiz logic...
var postData = { "score": score, ... };
if (number_of_answered_questions == total_questions) {
$.post("/saveScores.php", postData, function() {
if (score < 10) {
window.location.href = "page1.html"
}
else if (10 < score && score < 15) {
window.location.href = "page2.html";
}
});
}
How can I preserve images in a response to an email activity?
The images in the email show when viewed in CRM - they are added as attachments. When I click the 'respond' button, write a response, and send the response the images are stripped from the email and are not attached to the email.
I have been trying all sorts of things with JScript .
I would rather not have to write anything other than JScript.
This is possible with javascript. I don't know what you tried but this can be done. I.e. catch the send event of your form and create the attachment with Javascript.
Other options are:
You could use a workflow to attach the note of the parent email to
the response. But then you will be forced to save your email wait a
little while (execution of the workflow) and then send the email.
Write plug-in code (but you won't use anything else but Javascript
Javascript to delete attachment:
function deleteAttachments(){
var notesId = {GUID of notes};
var objNotes = new Object();
objNotes.DocumentBody = null;
objNotes.FileName = null;
objNotes.FileSize = null;
objNotes.IsDocument = false;
updateRecord(notesId, objNotes, “AnnotationSet”);
}
function updateRecord(id, entityObject, odataSetName) {
var jsonEntity = window.JSON.stringify(entityObject);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var updateRecordReq = new XMLHttpRequest();
var ODataPath = serverUrl + ODATA_ENDPOINT;
updateRecordReq.open(‘POST’, ODataPath + “/” + odataSetName + “(guid’” + id + “‘)”, false);
updateRecordReq.setRequestHeader(“Accept”, “application/json”);
updateRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8″);
updateRecordReq.setRequestHeader(“X-HTTP-Method”, “MERGE”);
updateRecordReq.send(jsonEntity);
}
I can access the attachments here: https:{org. URL}/xrmServices/2011/OrganizationData.svc/EmailSet(guid'3848cb4d-673f-e211-b9af-005056bd0001')/email_activity_mime_attachment
guid is the guid of the email.
The image is stored in d:Body as Base64.
Now all I need to do is rewrite img for each inline image with src="data:image/png;base64,theverylongstring...
All inline images will be preserved in the response as Base64.