Javascript + PHP + mySQL - javascript

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.)?

Related

How to notify the front-end of a website of the status of a back-end processing job?

I currently face the following issue:
After a user has uploaded his images, all images are processed through a script that optimizes every image (compresses it and removes EXIF-data).
I got everything working, the only problem is that the proces takes quite some time. I want to notify the user of the job status, e.g. a percentage of the processed images.
Currently, the user has to wait without knowing what's up in the back-end. What is the best way to accomplish this? I've thought about AJAX-calls, but I honestly have no idea where to start with implementing this, also because it looks like I need multiple calls (kinda like a heartbeat call on the processing job).
The application I am developing in is a Laravel application, I've made an API controller which handles incoming files via AJAX calls.
Any help is appreciated, thanks.
Laravel has Broadcasting for this. It uses websockets, redis or pusher to send events to the client.
This way you can send the client a message when the processing is done without them having to refresh a webpage all the time.
You'd be better off reading about the principle of how it's done, for example: Progress bar AJAX and PHP
Essentially the way it's done is that the job (processing images in your case) happens on the server through PHP. Your script will need to produce some sort of output to show how far through it is, e.g. echo some value for the percentage progress. The PHP script itself is responsible for producing this output, so you must work out how to calculate it and then code that in. It could be that it takes the number of images to be processed into account, and when each one is successfully processed, it adds 1 to a counter. When the counter equals the number of images, 100% done, or possibly some error messages if something went wrong.
On the frontend you could have an ajax script which reads the output from the PHP script. This in turn could update a progress bar, or div with some sort of percentage message - the value used coming from your PHP script.
Laravel - and other frameworks - have built-in methods to help. But you'd be better understanding the principles of how it works, such as on the link I posted.

PHP code to write current score to MySQL database

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.

Wait until a callback address is called

I am programming an educational web in PHP and JS and I interact with another webpage that corrects for me some programming exercises.
I don't know when this correction will finish, but this correction webpage calls a given address when the correction is available.
Is it possible to wait for that result with PHP or JS and then do some stuff (not just showing the result to the user), even if the user closes the tab?
Thanks in advance.
STEP BY STEP explanation:
A student is trying to do a programming exercise. The statement of the exercise is shown, as well as other details to complete it.
When he thinks he has reached a solution, he uploads his code. Then, he can wait (or not) for the correction to finish.
My web page uploads then the code file (with other files as well as an address to callback when it finishes) to the corrector webpage.
I keep waiting until the callback is made.
When the correction is finished, I do some stuff like assigning a grade to the student and, if he/she stayed on the same page, he/she can see details of the correction.
The correction is done by another webpage and I don't know when it would finish, but when it finishes it calls a given adress (for example: www.example.com/ex1sub1usr1 ).
The doubts are between step 2 and 3. It is possible to do all this process with PHP/JS? If not, what are the alternatives?
Updated Answer
Create a PHP script on your server which updates your grade database when visited with a specially formulated URL, eg. http://yourserver.com/update.php?user=2429&sub=1&ex=1
specify this as the target URL when you submit for correction
if you are restricted to your /ex1sub1usr1 format then just use regex to parse the URL
When user refreshes (or returns to your site) the data should be appropriately pulled from your PHP backend
For bonus points, you could have your submission screen (or the entire website) intermittently poll another PHP script URL on your server (with XHR) for an "updated" flag, and live update the page.
Considerations
Your only major concern will then be ensuring that the form data (ie. their code) is submitted completely. Consider using XHR to submit your form data and temporarily enabling a window closure warning until upload is complete.
Original "Answer"
Since there isn't much information to go by here, I will have to make a few assumptions:
you presumably can't reliably spawn a process to watch the associated results address
you don't need to notify the user immediately (push notifications), but they need eventually see their result, eg. when they return to your page
results stay around for a while
as you mention, this must work even if the user closes the tab
Given this scenario, I would merely check the results page when the user returns to your site.
Just store the results address in session vars - either via PHP or a cookie - then when the user returns you can perform any unfinished checks and update accordingly.
NB: Should further information surface in the question I will gladly provide further details
You can perform all necessary actions on a script behind the given address that is called by the remote website after the excersises have been corrected.
It is absolutely not possible to show/do anything on client side if the user has closed the tab.

Passing a JS variable to PHP Safely

I making a javascript game where the player builds up a score against a count down timer. When the timer runs out I display a form that show the score and lets the user enter they username (arcade style). I'm going to use the POST method send the user score to a php file that will store it somehow (database,textfile. or something). How do I prevent people from fiddling with the JS code and passing some new value thru that isn't the correct score (or something that isn't malicious).
At the very least, what are the safest methods on the PHP/reviving end to at least only accept and integer value?
That's a well known and difficult problem. I'm not sure it ever has a good solution. The user is the client is JS, so they have 100% control over what's sent to the server.
The only thing you can do and force, is server side validation. Don't just send the score. Send the path, the method, the steps, etc. Starting a session/game/level should also happen on the server, because the timestamp could be faked from the client.
You can make the whole game in JS, but start and end it on the server and remember all the steps. This might mean double step/path validation: JS (instantly) and server.
(I had the same problem with http://games.webblocks.nl/110 which stores steps (clicks) in g_stack.)

How can my ASP.NET page go back and forth from client to server code and back several times?

OK, the tite seems a little confusing, so I'll try to explain more thoroughly...
The process the page does currently follows the following sequence:
- User clicks a button
- server-side code goes retrieve data from the DB and exposes said data to the client using, populating, let's say, hidden fields.
- client-side code uses this data to fire up a an ActiveX component which performs a few tasks with the data provided.
And this works fine, however, we need to optimize the process because the ActiveX component is not fit to handle high volumes of data. We need to send data into "blocks" to the component, rather them send all data at once as it is done today.
However, I just hit a roadblock here, on how can I make the page go back and forth from server to client code multiple times? Like... "user clicks a button, server retrieves first block of data, sends to client, client executes ActiveX for the first block, client requests next block, server retrieves second block, sends to client, client executes ActiveX for the second block, client requests third block... and so on"? I can't get past the first request, since I can't register a client script block 2 times and expect AJAX to handle those multiple sequential callbacks...
Or is there a way?
This sounds more like an architectural issue than anything else.
What you should be doing here is:
1) User clicks a button. This is NOT a regular submit button. Just a plain old button that executes some local javascript.
2) Local javascript makes an AJAX request to determine how many records are available.
3) That javascript then does a loop based on the number of available records divided by the amount you want to pull per chunk.
3.a) Execute AJAX request for a chunk
3.b) Throw the data into your ActiveX control - which, btw, I really would suggest you guys think about getting rid of. There are so many issues with ActiveX that it's not even funny.
4) Repeat 3.a and 3.b until completion.
You'll notice that at no point was a full post back performed. You'll also notice that you shouldn't have to register any client script blocks.
Now the draw back here is purely in the ActiveX control. Can it be instantiated from javascript multiple times in a page or are you forced to only use a single instance?
If it's limited to a single instance, then you'll need a different approach entirely.

Categories

Resources