say, my PHP script needs some time to calculate its operations. I need to keep the client informed about the operation progress. An example can be PHP based file download, where I need to provide to client estimated time needed to finish the download, and the amount of data that needs to be copied.
In PHP I can calculate all the needed information. However, how to regularly update the client with this info?
Ideally, I would like to dynamically update JavaScript variable from within my PHP script. I read that this is not possible, so what options do I have then?
Possibilities that come to my mind:
Should I do regular AJAX calls from within my JavaScript into the PHP script to get the progress info?
Should I study for me yet unknown COMET methodology
Do the two above possibilities make sense? Is there any other more practical solution available?
Thank you in advance.
Yes, both of those options make sense.
There are lots of different COMET-style techniques, but one of the simplest is a long-running iframe. You have a PHP page that monitors the progress of the operation, and outputs something like this at regular intervals:
<script>parent.updateProgress(relevantUpdateInfo);</script>
...where relevantUpdateInfo is the information about the progress, and updateProgress is a global function on the page containing the iframe that shows the updated information in the UI.
When outputting the script tags, be sure to flush the output.
Related
This is more of a architectural questions. An external platform had product and price information for let's say, books. There is an API available to get this information.
What I read is that it should be possible to create a function in Javascript and connect the Javascript to a page where you want to show the data on my own website. This would mean that for each page request an API-call is made. Since the requested information only changes once a day maximum this does not sound the most efficient solution.
Can someone advise a better solution? Something into the direction of a similar php or javascript function that does the request on the background, schedule an update and import the data into mysql? If so, what language would be most common.
I need the solution for a Joomla/php/mysql environment
Here's a simple idea - fetch and store results from the API (ones you think aren't gonna change in a day), either on disk, or in the database, and later use these stored results to retrieve what you otherwise would've fetched from the API.
Since storing anything in frontend JS across page reloads isn't easy, you need to make use of PHP for that. Based on what's given, you seem to have two ways of calling the API:
via the frontend JS (no-go)
via your PHP backend (good-to-go)
Now, you need to make sure your results are synced every (say) 24 hours.
Add a snippet to your PHP code that contains a variable $lastUpdated (or something similar), and assign it the "static" value of the current time (NOT using time()). Now, add a couple of statements to update the stored results if the current time is at least 24 hours greater than $lastUpdated, followed by updating $lastUpdated to current time.
This should give you what you need with one API call per day.
PS: I'm not an expert in PHP, but you can surely figure out the datetime stuff.
It sounds like you need a cache, and you're not the first person to run into that problem - so you probably don't need to reinvent the wheel and build your own.
Look into something like Redis. There's an article on it available here as well: https://www.compose.com/articles/api-caching-with-redis-and-nodejs/
I have written a game.
It is an async turn based game where each person logs in at any time in the day, submits their orders, and at some time at the end of the day, the present turn is resolved.
However, the client side needs to know how to resolve previous turns, because it has to display it visually with all its many nuances. I have written this turn resolution in javascript.
Unfortunately, there is a secrecy element to the present turn. So I cannot just send all the data for the present turn to someones machine, get it to use its javascript functions of turn resolution in the code, then send it back to the database for everyone else to gather when they log in. Why not? Because that one person could catch the data, see the secret bits from other players, before allowing it to be sent back.
That means I have to completely rewrite my javascript code in PhP, so the secret turn resolution of the present turn can be done in private on the server.
So here is my question. To help me having to write my turn resolution code twice, once in javascript for the client (who needs the visual interpretation from the turn resolution) and again in php so the secret stuff of the present turn can be done in private, is there any way my php code can call my javascript turn resolution code from the php page?
Ie, I want my php page to be able to call a javascript function in a js file, which is all done on the server.
Do you really need to do it in PHP ?
If your hosting solution support node.js, you can reuse directly your javascript inside your server-side app.
It's called isomorphic javascript. (see : http://isomorphic.net/)
Another way to do it, would be to embed a javascript engine and call it from PHP (e.g : https://github.com/phpv8/v8js)
I'm updating a database via PHP with data that's being sent via ajax. Is there a way to tell whether the script that is sending the data is called by the page on which it is included (remotely hosted), or just being hacked into the JS Console by someone who's "inspected my elements" and trying to pull a fast one?
Thanks in advance...
Danny
There really is no way of telling between either of them, but you can make the job much harder to do.
But since you say that 'it won't start wars', working off of that, there are a few ways of 'securing' it.
Step 1 : Creating 'Verification' calls
If you aren't already, the very first step would be to implement a few preliminary AJAX calls that retrieve certain variables which are later used in the calls that follow, for example:
Call #1 Retrieves Security-Token
Call #2 Creates a cookie Security-Token-2
Call #3 Call to your php script with Security-Token encrypted with Security-Token-2
What your page would then do, would decrypt the sent text with the 'token' stored in the cookie and use that.
Step 2 : Adding extra logic into javascript
You can add some encoding-decoding logic into the javascript,
I'm not saying this is going to be hard to break, but It might be tough, especially if you obfuscate your code (We all know obfuscation is no good, but bear with me)
Step 3 : Don't keep any names
Another thing you can do is remove all the names from the AJAX variables, or better yet, the names can be different every time.
If you want to go even further, you can encrypt the names, and plus to the encryption add a component of randomness by introducing an IV, and storing the IV in the cookies (maybe even encoded for added security).
(EDIT) Found the 'dynamic name generation' solution I was looking for:
Dynamic Field Names in PHP
The solution was initially designed to fight spambots which 'autofill' certain fields, and if the field names look random it doesn't know which fields are 'traps', however you could use it to generate the names for your AJAX calls.
In the end though, it is always possible to crack, all one needs is enough time and money.
This is a youtube guide by phpcademy (now codecourse) that throughly explains how to prevent CSRF (Cross Site Request Forgery) in PHP.
It involves generating a new random token every time a form is submitted.
Afterwards you check if a token has been posted. If not, the request is not authentic.
EDIT: you needn't be worried about people seeing the token when inspecting the page, as you have your own (server side) way of validating your token.
I have some data that I want to display on a web page. There's quite a lot of data so I really need to figure out the most optimized way of loading and parsing it. In CSV format, the file size is 244K, and in JSON it's 819K. As I see it, I have three different options:
Load the web page and fetch the data in CSV format as an Ajax request. Then transform the data into a JS object in the browser (I'm using a built-in method of the D3.js library to accomplish this).
Load the web page and fetch the data in JSON format as an Ajax request. Data is ready to go as is.
Hard code the data in the main JS file as a JS object. No need for any async requests.
Method number one has the advantage of reduced file size, but the disadvantage of having to loop through all (2700) rows of data in the browser. Method number two gives us the data in the end-format so there's no need for heavy client-side operations. However, the size of the JSON file is huge. Method number three has the advantage of skipping additional requests to the server, with the disadvantage of a longer initial page load time.
What method is the best one in terms of optimization?
In my experience, data processing times in Javascript are usually dwarfed by transfer times and the time it takes to render the display. Based on this, I would recommend going with option 1.
However, what's best in your particular case really does depend on your particular case -- you'll have to try. It sounds like you have all the code/data you need to do that anyway, so why not run a simple experiment to see which one works best for you.
I use PHP and Javascript. In my website some results are processed server side some client side.
Using javascript only, prevents your website from being crawled correctly by search engines and using PHP only prevents correct real time response.
The problem is how to grantee both js functions and PHP functions give the same result? for example suppose there is a function which gives relative time:
JS:
function relative_time(timestamp)
{
...
}
PHP:
function relative_time($timestamp)
{
...
}
Keeping both functions matched with each other is not easy since I want to edit both. For example if both give us:
one year ago
And I change PHP only, to give me:
a year ago
Then JS is not updated too. Is there any standard way to ensure both will act in the same way?
unfortunately js function cannot be called on server side.
If there is some complicated logic, you should implement it server-side and just pull the results via AJAX. That way you only need to maintain the PHP code and provide a kind of AJAX API for access via JS.
I think you just need to make a decision where it is to be done, because if they do vary which is to be dominant ? (that's the one that should be doing it)
Also, how are you saving server load by doing it in both locations ?
Avoid this by making a decision for which code is to do it, failing that, Put a note in you code at both locations reminding yourself to update both locations ?