Ok, I am seeking a way for a shoutbox to trigger ONLY when a message is inputted into it by anyone.
Basically, we have control over what happens when someone submits a shout, but I don't want to use a Javascript interval (setTimeout() or setInterval()) functions to call this every x amount of seconds. Because every x amount of seconds it is hitting the database trying to determine if a shout has been made or not.
There MUST be a better method to do this that doesn't hit the database every x seconds in order to update the Shoutbox for everyone to see the shout.
This is where I need help, because our shoutbox is using too many resources on the server and causing the server to overload at times.
I have thought about a file instead... For example, when a shout has been posted to the shoutbox, a filename on the server changes to something, this filename than gets checked (instead of the database), and if the filename is different, than it should load up the shout. Perhaps, it can even place the shout within the file, instead of the database, and ONLY stick it into the database after another shout has been added to the shoutbox. Therefore, the last shout will always remain in the file, in text format.
Would this be a better approach for handling server overloads? But even still I would need to call an interval to determine if the file name changed. So this is still calling an interval, but do you think it would be better on the server this way? If so, what name should I use? Should I use the php time() function for this to name the file?
Are there any other ideas that someone could recommend to handle this. Preferably a way without using any intervals to update the shoutbox?
Please help, thanks guys :)
You might want to look into HTML5's WebSockets, but for non-compatible browsers I think you're stuck with continuously polling the server on an interval.
What you are getting close to with your descriptions of a possible solution is more like a server push than a page get.
I know you can achieve this sort of behavior using node.js with a Transfer-encoding: chunked. Check out the video at http://www.nodejs.org/ for a better example
Related
What do I need to do in order to make a call to an API, retrieve some data in JSON format and then store that data into a database. I know the specifics of this process, but the thing is I need this to be done at an interval of 5 minutes and without placing burden on the loading time of the website. So, I don't know the concept of how this is done because it obviously can't be done when the page is loaded, hence it has to be done by the server, but how ?
Any useful reading material regarding this topic would also come in handy. Thanks.
Take a look at the new web workers method in HTML 5.
http://www.w3schools.com/html/html5_webworkers.asp
You tagged this as a jquery question so I assume you already know how to make an ajax call. If you know how to make an ajax call Im sure you can figure out how to use setInterval to make this repeat every x number of seconds. But just in case take a look at this:
http://www.w3schools.com/jsref/met_win_setinterval.asp
This is assuming you want to do this on the page itself, otherwise as others have commented just set up a cron job.
So I'm writing a webpage that has a series of slot machines. You press on a particular slot machine and it tells you how much you won (or lost). I want to change these values a lot so I'm reading them in from a file using php so I can easily change the file to change the behaviour of the slot machines. (the file is just a bunch of numbers, eg "14,-3,6,9,-12,etc"
Now the way the slot machine works, as you can imagine, is that when you press on the machine, a value appears on the slot machine indicating what payout you get. And then a running total is updated by adding the value that just appeared in the slot machine. I am using javascript to achieve this affect. But in order to change the value of elements on the page, I need to know what to replace the elements by. So I'm thinking of sending all the data through to the javascript side of things.
But I've read many times that this is bad practice, and people usually ask "What are you really trying to do?". So this is what I'm really trying to do, manipulate values on a page, based on values in a file on the server. Is there a proper way to achieve this?
The better way is of course AJAX. You will be able to use the server values and update page content simultaneously. I would prefer using AJAX with JQuery as it takes care of cross browser issues and makes it easier to bring data from server as well. Here are some fairly simple tutorials about using AJAX with JQuery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
I am not clear how exactly your site works. But I think you can use ajax to do this.
When a user click a machine, javascript send a request "in the background". That is, using ajax. And then you can get the data returned by this request. Then you update data on your page. Have a look at Jquery ajax.
I wonder if the following would be a good Idea or rather contra-productive performance-wise:
An Ajax-Application, like for example a pagebrowser needs some language- and config-values, which are stored in the database. So each time, the user is using this app, in the ajax-script the mysql-query to get the variables is done again and again. concidering this for a pagebrowser, there might be like 10 or more requests (back and forward, back, forward, and so on), aka 10 x database-select, while it is needed only one time actually.
My idea was, to safe the config-vars in a session-array the first time, the ajax-app is requested. If the sessions-array exists, the mysql-query isnt done again.
if the user calls another regular page, these session-array is deleted again.
Now im not really sure, what would consume more server-resources, using sessions in the above described way for saving the vars teporarily, or just using a mysql-query to get the vars each time, the user klicks the ajax-app.
Thanx in advance, Jayden
If you working with massive amount of data, you could consider using Cookies as well instead of session for server resources, which will be stored in the user's local browser.
I'd bet sessions would be more effective, but the best way is to test and measure the different execution times.
I want to make a page that will show all the users who are looking at that page right now. Ideally, a database would store which users are on the page and websockets would be used to update when users enter and leave.
The problem is that I don't know how to tell when users are viewing the page. I was thinking that I would be able to tell when they arrived and when they exited and add/remove accordingly. It's easy to tell when they arrive; however, it's difficult to tell when they leave - especially because users might do something like open multiple tabs, close one but keep the other open.
What is the best way to do this? I am using PHP as my server-side language.
You can use the blur and focus events on the window to toggle a variable. However, IE does some quirks which you will need to work around.
As a fallback to not working focus events, you might add a mousemove handler to the document. This might also throttle an automatic timeout which detects the loss of focus just by the fact that there was no user interaction for a specific period of time. However, you will never be able to detect a distracted user that has the site open but looks at something else...
To detect the window closing, you can hook on the unload event. This might be unreliable, but as you are using Websockets your server can easily detect a closed connection.
Well, one thing you could do, especially if you are using websockets is do a heartbeat/ping to the server every few seconds if you really wanted. If you don't get that heartbeat, you know they are not on the page anymore.... however, getting a response doesn't mean they are looking at the page, it would just mean that it is open, possibly in another tab. There is no way that I know of that will send a response to the server if the person loses focus on the page and opens another tab/window.
As Tim mentioned, Firefox and IE will run javascript in the background tabs, so there's no surefire way by simple polling to tell if the user is actually "looking" at the page or just has it open somewhere. Although I know of no way to tell if the user is actually looking at your page, a potential solution might be to bind polling to actions. So you might have some variable
var timesincelastaction=0;
var threshhold = 20;
Then
setInterval("timesincelastaction++",100);
Then
function keepAlive() {
if(timesincelastaction > threshhold) {
$.ajax(...tell the server you are alive...);
timesincelastaction = 0;
}
}
Then start thinking of actions like
$('a').mouseover(keepAlive);
$('div').mouseover(keepAlive);
$(window).scroll(keepAlive);
$(video).play(keepAlive); // okay this isn't a real one but you get the picture
So then you just brainstorm on everything the user can possibly be doing on the page that requires their attention and use those as your benchmark.
This seems a little intense I know, there's probably some nice ways to optimize it. Just thinking out loud. Curious to see what others come up with.
Every time one of your PHP scripts run, some user or entity has requested to view a page on your site (this usually occurs every time your script runs).
It is more challenging to detect when a user has left your page, which is why most online indicators are simply a timeout, i.e. if you have not been active on the website in the past 5 minutes, you are no longer considered online.
You can get information about the user who requested the page with variables like $_SERVER['REMOTE_ADDR'] or if you already have an authentication system you should be able to pull a users username, store this info in a database with the username/ip as a unique key with a timestamp, and simply not count them as online if their timestamp is older than 5 minutes.
You could probably use jQuery- ajax, unload and load. The ajax request will trigger on load telling you that they are viewing, and trigger on unload telling you they are no longer viewing. The rest is left to you to figure out because it sounds like you already have a grip on it.
Note. same result should be achievable in plain JS. Such as, onunload. Google will find you the rest.
I am working in a tool in PHP that processes a lot of data and takes a while to finish. I would like to keep the user updated with what is going on and the current task processed.
What is in your opinion the best way to do it? I've got some ideas but can't decide for the most effective one:
The old way: execute a small part of the script and display a page to the user with a Meta Redirect or a JavaScript timer to send a request to continue the script (like /script.php?step=2).
Sending AJAX requests constantly to read a server file that PHP keeps updating through fwrite().
Same as above but PHP updates a field in the database instead of saving a file.
Does any of those sound good? Any ideas?
Thanks!
Rather than writing to a static file you fetch with AJAX or to an extra database field, why not have another PHP script that simply returns a completion percentage for the specified task. Your page can then update the progress via a very lightweight AJAX request to said PHP script.
As for implementing this "progress" script, I could offer more advice if I had more insight as to what you mean by "processes a lot of data". If you are writing to a file, your "progress" script could simply check the file size and return the percentage complete. For more complex tasks, you might assign benchmarks to particular processes and return an estimated percentage complete based on which process has completed last or is currently running.
UPDATE
This is one suggested method to "check the progress" of an active script which is simply waiting for a response from a request. I have a data mining application that I use a similar method for.
In your script that makes the request you're waiting for (the script you want to check the progress of), you can store (either in a file or a database, I use a database as I have hundreds of processes running at any time which all need to track their progress, and I have another script that allows me to monitor progress of these processes) a progress variable for the process. When the process begins, set this to 1. You can easily select an arbitrary number of 'checkpoints' the script will pass and calculate the percentage given the current checkpoint. For a large request, however, you might be more interested in knowing the approximate percent the request has completed. One possible solution would be to know the size of the returned content and set your status variable according to the percentage received at any moment. I.e. if you receive the request data in a loop, each iteration you could update the status. Or if you are downloading to a flat file you could poll the size of the file. This could be done less accurately with time (rather than file size) if you know the approximate time the request should take to complete and simply compare against the script's current execution time. Obviously neither of these are perfect solutions, but I hope they'll give you some insight into your options.
I suggest using the AJAX method, but not using a file or a database. You could probably use session values or something like that, that way you don't have to create a connection or open a file to do anything.
In the past, I've just written messages out to the page and used flush() to flush the output buffer. Very simple, but it may not work correctly on every web server or with every web browser (as they may do their own internal buffering).
Personally, I like your second option the best. Should be reliable and fairly simple to implement.
I like option 2 - using AJAX to read a status file that PHP writes to periodically. This opens up a lot of different presentation options. If you write a JSON object to the file, you can easily parse it and display things like a progress bar, status messages, etc...
A 'dirty' but quick-and-easy approach is to just echo out the status as the script runs along. So long as you don't have output buffering on, the browser will render the HTML as it receives it from the server (I know WordPress uses this technique for it's auto-upgrade).
But yes, a 'better' approach would be AJAX, though I wouldn't say there's anything wrong with 'breaking it up' use redirects.
Why not incorporate 1 & 2, where AJAX sends a request to script.php?step=1, checks response, writes to the browser, then goes back for more at script.php?step=2 and so on?
if you can do away with IE then use server sent events. its the ideal solution.