So long story short, im trying to build a chat application....well its already built kind of but, ive been trying to implement AJAX into it. Essentially so that as the messages come through from the db when a user posts it, that it reflects on the page automatically without page refresh.
on the javascript side the only event i could think of that would run without user input is the javascript setInterval() function that i have set to repeat # every 5 seconds for now.
on the PHP side which has the messages (echoed out), i have a statement that only displays the
last 10 messages.
The problem is that, every 5 seconds, it spits out the same 10 messages. over and over...broken record kinda lol. anyways so what i dont know/cant figure out how to implement, is a filter kind of, or SOMEthing that says "
hey only show me the last 10 messages and update ONLY when there is
new content.
"
So what i need is something( i assume javascript since its the one refreshing the page) that says only display the latest x posts only when its new content. I was thinking maybe an if/else that compares one value to another and then if false/true, run the refresh...but
what do i compare to???
as you can see, im stuck.
i dont post the code because its alot...dont want to put two chunks of code here but essentially the PHP reads rows from a DB section, and posts the latest 10 posts from the db via echo.
and the Js has AJAx commands that gets those messages and posts them on the page.
And again, both work except for the re-posting the same 10 messages on ajax /js refresh.
any tips,links, LOGIC...anything to help me get through this hump i gladly and humbly appreciate.
P.S - if you need to see code. let me know and ill post it but i think its pretty clear.
Thanks in advanced.
so webchat clients do this thing where they make a request to the server and the server lets it hang, as if its taking a long time to process, but instead, its waiting to see if someone else posts a chat or what have you, the moment it does, it replies to the user, if the timeout max is reached, it just allows the connection to actually timeout, at which point the javascript causes it to fire again. this eliminates the nasty, make a call every 5 sec feature for starters.
Keep a last returned timestamp in your javascript, and when you need to update the clients, send that along, and use that as your sql conditions:
select * from chat_logs WHERE datetime > $postedValueFromClient # AND YOUR OTHER CONDITIONS
Give that query results back to your clients, and update the last timestamp as well.
I can't help you further since I don't have any code, but that's one way of implementing it.
I'd fetch 1 line at a time and remember the ID of the last line that was received, also make a column in your table for instance read and set it to 1 or 0, if the message was receive set to 1 and only look for messages that have read set to 0.
MySQL statement:
SELECT * FROM `table` WHERE `id` > `lastID` AND `read` = 0;
Related
I am currently working on a project that runs online tournaments. Normally admins of the site will generate brackets when it is time for the tournaments to start, but we have run into inconsistent start times, etc. and i am looking into proper ways to automate this process.
I have looked into running cronjobs every x min to check if a bracket needs to be generated but i am worried about issue when it comes to overlapping cronjobs, having to create/manage cronjobs through cpanel etc.
I was thinking about other solutions and thought it would be great if a user could load a page, the backend checks timestamps and determines if the bracket should be generated. An event is then fired/set to begin the auto-generation process elsewhere so it does not impact user load times. I just do not know the best route of going about this.
PS: I just need an idea of the direction i should be looking into so i can learn how to solve this issue i am not looking to copy and paste code. I just haven't been able to find anything. All of my search results provide cronjob examples.
EDIT
After thinking about things could using this work?
$(document).ready(function() {
$.ajax('Full Url Path Here');
})
I don't need to pass user input, or return any data i simply need a way to fire an event, it would be easy to include this only when needed via a helper class. Also i won't necessarily have to worry about users attempting to access i can restrict the route to ajax only requests and since nothing is needed/used on input or returned as output what can happen?
You could do it everytime a user loads a page (idea not tested, but theoretically possible):
1) Create a file and store the timestamp of the last time you updated the database.
2) Everytime a user loads a page, read that timestamp and check if 15 minutes passed.
3) If 15 minutes passed: Run a background script (with shell_exec?) that will do what you want and update the timestamp when it's done executing.
One obvious flaw with this system is that if you have no visitors in let's say a 30 minute frame, you will miss 2 updates. Though I guess that if you have no visitors you also have no point in generating brackets?
I'm working on a basic lamp(willing to change) website , and I currently need a way to run some function on the server that runs for several hours per user, and every X hours it needs to query the mysql database to see if the value for that user has been updated, if it hasn't it need it to insert a new record in the database...I also should mention that the 'every X hours' can change per user too, and the total runtime of the function per user can also vary.
So basically I need a function that runs continuously on the server for few hours per user. What is the best way to do this? I want the site to be able to support many users (like 10000 +).
I'm willing to try new technologies for every aspect of the site, I'm still in the design phase and I was looking for some input.
I've looked at cron but not really sure how well it would work when dealing with so many users...
edit: Here is a typical scenario of events;
User presses button on the website and closes the browser.
Server starts a timer from when they pressed the button, now
the server will check if that user has pressed a different button within a given time frame (time frame can change per user), say within 30 minutes. If they didn't press the other button then the server needs to automatically insert a new record in the database.
The script will need to continue running, checking every 30 mins for say the next 5 hours.
Thank you!
Cron would work as well as you can code the page it will run. It's not a cron limitation.
The question is ambiguous btw. Maybe explaining your full scenario would help.
Meanwhile, my suggestion would be to set up a scrip that allows you to manually check what you need to check.
You definitely need the DB to be InnoDB optimized with proper indexes to be able to support 1000 plus users.
To alleviate the number of calls to the database, a common practice is to run scripts only on what you are interested (so in the case of users you would only select those who have logged on in say the past 3 hours)
That's achievable in 2 ways, a simple select statement, or by adding entries to a specific table on the login page, and remove them after the automated script has finished running.
All of this is pure theory without understanding exactly what you need to do though.
You are telling what/how you want to do, but not why you want to do it. Maybe letting us know why could lead to a different how ;)
However, what you can do is still use cron (or anything similar). The trick is to have
a last_interaction timestamp column
a maximum_interval column
a daily_runtime column
in your users database. Not optimized but you are in the design phase so you shouldn't pay too much attention to the performance aspect (except is explicitly required).
Hi I want to create a script which detects if certain rows in a mysql table no longer are empty.
I guess i need to run a php script every 5th second which checks certail table rows. If any of them are empty it should continue updating. If not it should redirect to another php page which shows the updated/filled tables.
Any ideas on how to do this?
It is kind of like the game "who wants to be a millionaire" where x persons gets the same question which they need to answer. Answering them will store their answers in certain table rows. When these rows are not empty the main page needs to show all answers and how long time they have spent answering them.
I just need the updste each 5th second script which returns "true" or "false" (if any of the rows are empty).
Cheers,
Mads
Polling table every 5 seconds sounds very wrong.
You should rethink you workflow on how you react to external events.
If you can afford changing your database to PostgreSQL, it offers good solution for this problem. Namely, you create trigger on table of interest, and inside that trigger use NOTIFY.
Another connection that wants to react to table changes, will use LISTEN to register for notifications and then simply go to sleep using select() on connection handle. Then, once trigger has fired, this connection will immediately receive this event and can react on it right away.
This approach allows to use exactly 0 CPU time on both server and client and yet react on changes immediately.
A way to do this :
Set a JavaScript timer when the player answers the question (displaying a 'waiting for other players to answer' message for example) and triggering an asynchronous query to a php script (let's say waiting.php) every 5 seconds. If waiting.php returns 0, nothing happens. In waiting.php returns 1, player is redirected on the page witch will display all the answers and times
In waiting.php, write something like that :
echo (current(mysql_fetch_row(mysqli_query('SELECT count(*) from responses WHERE questionId = '.$_GET['QuestionId'].' AND answer_field IS NULL'))) > 0 ? '0' : '1');
I've decided to create a web based chat system for the experience. I'm using a mixture of AJAX(jQuery), PHP, and JSON to transfer the data. Now that I've started thinking about certain things, I've come to a mind block.
Right now, I use javascript to post the last loaded message id to a php file that queries the data and echoes new posts in json and then displays those posts in order on the page. However, the dates don't reflect the current time for the user. Since I use php to get the current time, I have no idea how to display the correct time to the user which takes into account of their time zone. Second, how would I incorporate a who's online list with this method? I could create a separate table and update it when a user creates a session and delete their name when they end the session; but what if they don't close it properly? Should I just add their last sent message into the the table and if it's been about 5 minutes since their last message consider the user disconnected? Lastly, is the method I'm using to collect new posts efficient? This there a better way to go about this? I appreciate any input.
This seems related: Determine a User's Timezone
I'm going to make you go there for the code snip so you give proper credit with your upvotes.
I get the impression that Javascript is the best/easiest way to get that data.
What I would probably do is use GMT or some other fixed time zone for all your server stuff and then just adjust that with js once it hits the browser depending on their time zone. Either that or just collect it once at the start of the conversation and adjust your output accordingly. There might be advantages to either way.
Edit:
Oh yeah, about the "who's online" I think you're headed in the right direction. I might suggest 2 lists. "Who's active" and "Who was active recently"
That way you can put people inactive after 5 mins and consider them disconnected after 10 or something. I guess it's about the same but it seems more accurate to me somehow.
The other option would be to set an ajax request to automatically fire of a request every minute or so. When they stop then you know the user is gone.
I am trying to create an Online Quiz script like expert rating test on ODesk or Elance.
I want to track the time, means how much time have passed and left. I also want to stop the time counter, if the user internet connection is disconnected, so that he can start from where it was disconnected.
One last thing how to disable the last questions, which were attempted by the user. I am using PHP, MySql for it.
Your ideas will be great help for me.
Thanks in Advance
I've done something like this. Basically you have the right starting idea. Create a timer table which stores start times, test id and user id.
On each page load or AJax call you check the current timestamp minus the start time to see how long has gone since they started. If at any point it passes your limit you redirect them to the test complete page. Don't worry about the internet connection its actually irrelevant. This basic rule covers all.
I've done something related to this. you have to think about this to begin the idea. Create a timetable that stores begin the time, user id, or testing id.