PHP code to write current score to MySQL database - javascript

I have a website where you need to create an account and login to play the game. I have PHP that refers to a MySQL database with a column for UserId, Username, firstname, lastname, password and score. The login works fine. Then, you are taken to the html document that contains the game. It is somewhat like cookie clicker, where your objective is to get the highest score possible through interacting with an object.
I have a score variable called "clicks" which increases quite rapidly.
I have some javascript code that reads;
if (clicks%5==0) {
sendScore()
}
What this means is when clicks is divisibly by 5 it activates a function called sendScore. It activates the function every 5 increments because I assume sending data to the table multiple times a second would be demanding too much from the server. This function will write the current players score to the MySQL table column named "score", the row in relation to the players UserID. UserID is a number that is generated when an account is created so that the user's account can be easily referred to.
I know its just me overthinking it, but I cannot seem to write a working piece of PHP code that I can link to the sendScore() function that sends the player's current score ('clicks' javascript variable) to their score column in the MySQL database.
Any help would be appreciated.
Thank you.
NOTE!!!!
The request to send info has to be an AJAX request. Maybe this is why it doesn't work. I am used to writing forms, but forms would refresh the page. Can anyone help write an AJAX request for this situation?

What is your current sendScore function?
It is kind of hard to give a detailed answer without more of your code, but I'll try:
Your sendScore function will need to send a request to the PHP script that will handle this request. You can do that either using pure JavaScript, using XMLHttpRequest. More on that here: http://blog.garstasio.com/you-dont-need-jquery/ajax/. However, you can also use a framework such as jQuery to do some of the heavier lifting. More on jQuery and AJAX functions (specifically post-requests) can be found here: https://api.jquery.com/jQuery.post/.
Then you'll need a PHP function that can handle the request. You have to point your JavaScript function (that performs the POST request) to the URL of this script. Then you can process the information sent by your JavaScript just as you would process a 'normal' form.
To get your values from JavaScript to PHP and vice versa, it's probably easiest to use JSON, as both JavaScript and PHP handle JSON nicely these days, and it's a lot easier than XML.

Related

Javascript + PHP + mySQL

I am a beginner doing a single player browser game as a hobby mostly to learn javascript + php + mySQL.
For some reason I want front end to be done exclusively with javascript (drawing levels, inventory, etc.) Broadly speaking, I will be heavily manipulating DOM using jQuery.
In the backend there is a mySQL database. In the middle there is PHP which I see serving two purposes: i) speak to DB , ii) validate logic and respond to requests coming from front end (i.e javascript).
For example, intended flow is:
user wants to open a door and interacts with a relevant element in the browser - clicks on it.
Action requires validation. AJAX call to PHP saying “user wants to open the door”.
PHP check with DB to see if the user has got a key in inventory, does some backend logic checks to ensure that the right door can be opened and responds, e.g. with “1” , meaning that the user has got the right key and action is "valid". PHP could also tag this door's status in DB as "unlocked" which means that player does not need a key to pass through it again. Key is removed from inventory record in DB.
Javascript receives PHP response and renders inventory and location anew (e.g. image of a key is now missing in player’s inventory and the door is drawn differently), could possibly start a dialog on screen and perform other DOM manipulations.
I would really appreciate some advice on how to handle the “session part” of such setup. Obviously, if there is a number of players playing the game at the same time, PHP needs to look up records in DB relevant for the player, which would be normally used by userid attribute in $_SESSION.
I understand that javascript can only operate with cookies and not with sessions. I would think that a cookie could be generated with some random ID and this random ID would be written to DB. Then, when AJAX posts to PHP, this ID would be included into the post and used to look up things in DB. Then PHP would respond and front end would be changed accordingly to the player affected but not for everyone else. Am I on the right track?
Would be most happy to have some small piece of code which could illustrate this or another solution.
On another note, would such setup be OK in terms of performance or should I consider fully using .php and leave JS do to some minor job (e..g initial validation of forms before posting, etc.)?

getting data from database and displaying on another page

***** COMPLETE MODIFICATION OF THE PREVIOUS QUESTION ******
I have been developing an appointment system over the past few weeks using php, mysql and javascript. I've come across a problem when trying to insert data into a table. I am using javascript on a php page to send a GET request to a php file which generates a table from database records. I have
I can't understand some of questions but as far as I know you want to call a data from the page?
You want to call the data from the specific users? If yes, you must use $_GET to get ID then you can call the data you want.
Please elaborate more regarding your question.

Classic ASP and Javascript Integration

I'm currently using Classic ASP and youtube javascript API in order to pull information of videos and store them into a database, however I need to know if some of the next steps are possible, or if I would have to convert to another language.
The information I am seeking to download into my SQL 2012 Database currently exceeds the maximum space allowed, meaning I can only send about 50 of my 1700 results (and growing) each time. Prior to the space cap, I would simply keep running the next page function until there is no more pagetokens and simply upload all the data, however, now I must do it in small steps.
My application currently works like this: Javascript creates hidden forms->Forms are submitted->classic ASP queries form and moves information to database
By directly editing the code I can modify which 50 results I send to the classic ASP, but I'd like to be able to do this without modifying code.
So my question is this: Is it possible to send a url query of sorts to javascript so that I know what results I have sent? Or is there a better way to circumvent the space issue aside from rerunning the javascript each time?
The error I get when attempting to spend too much information is:
Request object error 'ASP 0104 : 80004005'
Operation not Allowed
I apologize if this question seems a little vague as I'm not entirely sure how to word this without writing a 5 paragraph essay.
You could add a redirect on the ASP doing the downloading. The redirect can go back to the javascript page and include the number of results processed in the url like so:
Response.Redirect "javascript.asp?numResults=" & numberOfResultsSentSoFar
Then on the javascript page include some ASP to extract the number of results processed
dim resultsProcessed = Request.QueryString("numResults")
Then you can feed it into javascript like so:
var currentResultIndex = <%=resultsProcessed%>;
However, a better way might be to use AJAX to send the first 50 results and wait for a response from the ASP and then send the next 50.

Prevent fake looping ajax requests to PHP

On my website, I have created a comment section for blog posts. Users can write comments, click a button, and an AJAX request will be sent to PHP containing the data in JSON. The PHP will process & validate the data and then insert it into the database. On success, all comments are retrieved from the database and, using JQuery, all of the page's comments are reloaded.
The problem is that anyone can come along and, using their browser's console, forge an AJAX request, fill in their own JSON, and send the request to PHP. If done like this, all that happens is my client-side validation is useless. The server-side validation would still work. However, there's a bigger problem.
for(var i = 0; i < 10000; i++) {
//ajax request
}
The user can very easily insert thousands and thousands of records into my database instantly.
Does anybody have any suggestions on how I can prevent something like this from happening? It must involve creating something on the server side that can't be guessed by a user, and somehow checking against that during an AJAX request. I'm just not sure how exactly to go about this.
Thanks for the help.
The only way for you to be safe in this respect is to add a CAPTCHA.
This will prevent mass / automated posts. One possible library to use is Securimage . It is simple to use and integrate. You can have it running in 10 minutes with your AJAX stuff.
Relying on other means such as cookies or client side validation of some sort is risky, if possible at all. For instnace KA_lin 's solution can be compromised in 5 minutes: a malicious user can be sending forged cookies that will always have a page count of 0 and thus will always be allowed to post. Or even worse, he could create a small program that will post to your page without sending any cookie at all. The above code will create a new cookie and accept his post, every time ...
I would add a session variable containing the number of posts a user makes, given many pages you can form something like $SESSION['page_id_total_nr_comments'] and track this number, add a config variable that let`s the use to add a maximum of X comments per article for example:
function canUserAddComment($pageId){
$maxAllowed =......;
if(!isset($SESSION[$pageId+'_nr_comments'])){
$SESSION[$pageId+'_nr_comments'] = 0;
}
if($SESSION[$pageId+'_nr_comments']< $maxAllowed){
$SESSION[$pageId+'_nr_comments']++;
return true;
}
return false;
}
OR
On save get the number of comments a use already made on the article and decide if ha can make another(still with a config variable)

How to improve my ajax script to get data faster

I want to do is when a user fill a valid email in the textbox and click the send button it will send to his email his password directly.
My problem is the result takes 3 secs or more in order the ajax script receives the result specially when the php echo 0 to ajax. Does anyone know how to make my code faster?
Make your connection persistent using mysql_pconnect.
Return only changed data and apply the difference instead of returning whole set of data.
Also, instead of hitting database often, you can cache as much as you can.
Also, refer to PHP micro-optimization tips.
Asynchronous request doesn't mean the request are fast, it means you can continue with your code flow without waiting for the response.
Running a query on your database and sending a mail will take time.
The problem might be not in your ajax code.
Not really know how many records in table tbl_mkash. For a lot number of records (million of records) indexing field elog_email might speed up the query.

Categories

Resources