PHP Mysql: Avoid overflow on pageviews? - javascript

So I have certain profile pages that needs to have page views. I stored the view data in mysql and php (actually laravel). Basic idea is to add view by 1 every time the profile is visited.
Basic idea is to add a php code in the profile page, like
$page->view += 1; $page->save();
But what if the user hits f5 several times? It will cause the query to run a lot and I fear it will eventually slow the app.
I was thinking of making a prompt with js when user hits f5 and an ajax call to add the view. But I was wondering if there is a better solution (like, how did youtube do their views)?

You can count the views after a certain amount of time on the page.
To achieve this, you will need a delayed javascript function like:
setTimeout(function(){countView()},3000); (3 second delay)
Where countView() should be an ajax call to a function that runs $page->view += 1; $page->save();
And since Ajax calls are asynchronous, the execution will not delay your application flow, although a simple increment on a page-view table should not do much harm in terms of performance

This will work as long as the user doesnt delete the cookies.
if ($_COOKIE['returning']!="yes")
{
// first visit!
}
setcookie("returning", "yes", time()+360000);
Another way would be to log the IP in a database and check if user already visited, but the code is more complex than i can post right now. I will edit the post later if accepted.

Related

1 video view = 1 Parse request? How to improve that?

I'm working on an app a little like Vine, where several looped videos are displayed on the screen of the user. I need to count one view per loop. It means, if the user repeat the video 5 times, it will count 5 views. And this is the model I want to use for every videos of my app.
I use Parse for my back-end and a webview to show the videos. It means that I use Javascript to send requests to Parse, with Ajax calls.
My problem is that I don't really know how to limit the number of requests sent to Parse when I add a view on a video.
Maybe I should save the video views to a MySQL database and then, once a day with a cron task, save the MySQL results to Parse? I don't really know how to proceed, but I really need to limit the number of requests to Parse.
How would you design this?
Thanks!
My first thought is to not optimize too early. There should be plenty of time, as you accrue zillions of users, to improve the design.
If you want to improve it early (and still use parse), keep the object that tracks views "pinned" locally (see this blog entry). Update the view count as often as needed, then update parse on an NSTimer.
The app may become inactive at any time, and if unsaved views have been counted since last time the timer fired, then there's one more problem to solve. The app delegate gets told that applicationDidEnterBackground, and can request a moment to finish "one last thing". See here under "Executing Finite Length Tasks".
There (iIn the dispatch block suggested by the sample code), save the object that counts views (saveInBackgroundWithBlock:), invalidate the timer, and tell iOS you're done with [application endBackgroundTask:bgTask];
What I should is store the video's somewhere else and save 1 view per click.
You can save this click in the background using something like this:
userClick.saveInBackground()
It saves the click in a background proces so the user doesn't have to wait for the sync with Parse.
note: You should use Bolts (https://github.com/BoltsFramework/Bolts-iOS) to get saveInBackground() working.
* edit *
Maybe it's smart to sync with parse every x amount of clicks, maybe 5 or 10. To limit the amount of requests.

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.

Updating a page when data changes

It has been a long time since I have worked with PhP or Javascript and I want to build a website that runs on a server with MYSql that can update the page when the data in the MYSQl table changes.
I am not sure how to do this, if anyone has any ideas I'd love a boost.
assuming this data is being gathered using an SQL SELECT statement,
move your statement and the way in which it displays the results into a different file.
then you can load the results from the query into a div using jquery .load
$("#someDiv").load("somefile.php");
If the data is not being updated from the page in which you want it auto refreshed, use setInterval
$(document).ready(function(){
setInterval(function(){
$("#someDiv").load("somefile.php");
}), 2000);
});
with 2000 meaning it will run every 2 seconds.
If you are updating the data and want the updated results shown without the need for a page refresh, use ajax and in its 'success' function call:
$("#someDiv").load("somefile.php");
You want a webpage to be notified of a change in the server. More specifically, you want the data in your page to be refreshed when the data in your database changes.
You have at least two options:
You write some javascript so that you browser periodically asks (polls) the server for changes via ajax (as another user has already explained). You could even consider long polling.
or...
You make use of websockets, which will allow your server to push the data to the client whenever the server wants.
You may want to take a look at the many posts in SO which discuss this matter.
Refresh content automatically if the database changes
Automatically refresh browser in response to file system changes?
How can I refresh a page when a database is updated?

Poor Performance in Loading content using AJAX

I need your help badly in determining the cause of this problem. This is a hotel management system that keeps track of checked in guests and monitors them if their time is up. I'm using setTimeout as suggested by Mr. A. Wolff (Slow website after some time (with ajax interval of 10 seconds)) in this discussion. It's reloading the content every 5 seconds now but as you can see, the debugger is consuming 10 seconds in getting 56KB of data.
The problem still exists. I have done my researches about modals and timeouts and I am close to giving up. I just need a clue on where to start.
The computer is where the files are located. Technically, it's a server and at the same time, being used as a client for the system.
Here's a screenshot for the debugger. Thank you.
UPDATE:
I removed the setTimeout from the function itself so basically, nothing's reloading the page. Then I opened a checkin page, things got faster, and I mean so fast now. So I think this is what I need to do, I need to stop the function from reloading the page IF I OPEN A MODAL. The reason is that, if the modal closes, it's going to reload the PAGE anyway. So it must be a good idea to stop the recurring function when a modal is opened. Any suggestions?
UPDATE 2:
Here's the link of the script being executed:
https://www.dropbox.com/s/azi51w0pzp69kgh/checkin.php
Here's the live site: http://greenenergiesllc.com/temp
Login: removed by moderator
Password : removed by moderator
i suggest you don't use settimeout,use setinterval for 5 sec instead of it.
if you pull large data from server you must use json.
and also don't create js timer in same time,the server couldn't response over ajax requests.

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