Data synchronisation between webpage clients - javascript

First I'll describe my problem:
I have a web-page, that continuously writes data as json in file. Everything is ok while I have only one entity of this web-page, but as soon as second client connects to this web-page and changes values both entities write to same file and my C program that reads this file(used as pipe) goes crazy showing data from one page and then from another(predictable).
Sorry, if there already was such question, but I don't how to describe it in few words to ask google:)
So first my idea was first to read that file with web page to actualize data and then save changes. But actualizing data twice in one second would make impossible to change something on web-page(you start writing, but web-pages actualizes and cleans your changes).
Is there a way to synchronize data between clients of the same web-page, but allowing them to make changes too

Related

Display result (image) of computation in website

I have a python script that generates a heightmap depending on parameters, that will be given in HTML forms. How do I display the resulting image on a website? I suppose that the form submit button will hit an endpoint with the given parameters and the script that computes the heightmap runs then, but how do I get the resulting image and display it in the website? Also, the computation takes a few seconds, so I suppose I need some type of task queue to not make the server hang in the meanwhile. Tell me if I'm wrong.
It's a bit of a general question because I myself don't know the specifics of what I need to use to accomplish this. I'm using Flask in the backend but it's a framework-agnostic question.
Save the image to a file. Return a webpage that contains an <IMG SRC=...> element. The SRC should be a URL pointing at the file.
For example, suppose you save the image to a file called "temp2.png" in a subdirectory called "scratch" under your document root. Then the IMG element would be <IMG SRC="/scratch/temp2.png"> .
If you create and save the image in the same program that generates the webpage that refers to it, your server won't return the page until the image has been saved. If that only takes a few seconds, the server is unlikely to hang. Many applications would take that long to calculate a result, so the people who coded the server would make sure it can handle such delays. I've done this under Apache, Tomcat, and GoServe (an OS/2 server), and never had a problem.
This method does have the disadvantage that you'll need to arrange for each temporary file to be deleted after an expiry period such as 12 hours or whenever you think the user won't need it any more. On the webpage you return, if the image is something serious that the user might want to keep, you could warn them that this will happen. They can always download it.
To delete the old files, write a script that checks when they were last updated, compares that with the current date and time, and deletes those files that are older than your expiry period.
You'll need a way to automatically run it repeatedly. On Unix systems, if you have shell access, the "cron" command is one way to do this. Googling "cron job to delete files older than 1 hour on web server" finds a lot of discussion of methods.
Be very careful when coding any automatic-deletion script, and test it thoroughly to make sure it deletes the right files! If you make your expiry period a variable, you can set it to e.g. 1 minute or 5 minutes when testing, so that you don't need to wait for ages.
There are ways to stream your image back without saving it to a file, but what I'm recommending is (apart possibly from the file deleter) easy to code and debug. I've used it in many different projects.

Should I load html file with data or load html and then request data (with AJAX)

When creating a html file inside of a XAMP software system, I use to load in the first place the data from PHP that is critical to use the web page (for example, saving the user id in javascript to make AJAX requests to server) and then, after showing the body to the user, load irrelevant data for execution, but useful for the user (for example, a table with the last bought products of the user) from server with AJAX. That's it: first show html file to user and then ask for the remaining data to server.
I found this is maybe some kind of silly, because you could show all the html file with the data loaded from PHP, Perl, whatever.
But here is the point: is one option more correct than the other one?
I think that, maybe, the first option will be more user experience oriented (because, the user has the feeling of fast loading, he watch the html file early because he doesn't have to wait to load php data too before getting the html file). I read somewhere that javascript (and html) is oriented to UI, that's why you shouldn't, for exaple, block the UI with semaphores to wait an async task to be completed.
But maybe someone of you guys could give me a reasoning to be using the second option (load first PHP data and then show html) instead of using the first one; well done software is good software.
Thank you.

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

Upload files asynchronously then save data about it

I am building a way for users to upload tracks with information about that track but I would like to do this asynchronously much like YouTube does.
At the moment there is an API endpoint of tracks that accepts a POST request with the uploaded file and all the meta data. It processes the track, validates everything and will then save the path to the track and all of its meta data in the database. This works perfectly but I am having trouble thinking of ways to do this asynchronously.
The user flow will be:
1) User selects a track and it starts uploading
2) A form to fill in meta data shows and user fills it in
3) Track is uploaded with its metadata to the endpoint
The problem is that the metadata form and the file upload are now two separate entities and now the file can finish uploading before the metadata is saved and vice-versa. Ideally to overcome this both the track and metadata would be saved in the browser as a cookie or something until they are both completed. At that point both would be sent to the endpoint and no changes would be required at the back end. As far as I am aware there is no way of saving files client side like this. Oh apart from that filesystem API which is pretty much deprecated.
If anyone has any good suggestions about how to do this it would be much appreciated. In a perfect world I would like there to be no changes to the back end at all but little changes are probably going to be required. Preferably no database alterations though.
Oh by the way I'm using laravel and ember.js just in case anyone knows of any packages already doing this.
I have thought about this a lot few months ago.
The closest solution that I managed to put together is to upload file and store it's filename, size, upload time (this is crucial) and other attributes in DB (as usual). Additionally, I've added the column temporary (more like a flag) which would initially be set to TRUE and only after you would sent meta data it would be negated.
Separately, I've set the cron job (I used Symfony2, but in Laravel is all the same) that would run on every 15-30 minutes and delete those files (and corresponding database records) which had temporary = TRUE and exceeded time window. In my case it was 15 minutes but you could set it to be coarse (every hour or so).
Hope this helps a bit :)

Getting a file out of a local web page

This is what I'd like to achieve from a local page:
Enter data in a textbox
Transform the data (the outcome may be not a text file)
Get the transformed data back.
Directly writing on a local file is clearly out of question for security reasons. I know HTML5 has a FileWriter API but it's not supported on many browsers (and I think for a good reason).
I thought about creating the data as the content of one of the page elements (say a <DIV>) but then I am at loss on how to send that data back.
In essence, I feel I had to mimic the usual http request/response process while always remaining on the client side.
I start thinking that this is not possible at all, any suggestion?
One way that would take you near your desired outcome is by using data: URI scheme (http://en.wikipedia.org/wiki/Data_URI_scheme)
window.open("data:text/plain;charset=utf-8,"+textToPrint);
That opens a new tab with the text you want to save, you just need to click save or ctrl+s to save the text in a .txt file.

Categories

Resources