php - How to share data between clients using JavaScript? -
i have variable json, want make on php page able see same variable contents.
this code should explain more of situation. (i trying make page won't reload)
var chats = []; var j = jquery.noconflict(); j(document).ready(function() { setinterval(function(i){ var txt = ""; var x; (x in chats) { txt += chats[x] + " <br />"; } document.getelementbyid("json").innerhtml = json.stringify(chats); }, 1000) }); j(document).ready(function() { j('#post_button').click(function() { $text = $('[name=message]').val(); $sender = $('#texta').val(); chatstuff = { "sender" : $sender, "message" : $text, }; chats.push(chatstuff); $('[name=message]').val(""); }); });
so when document.getelementbyid("json").innerhtml = json.stringify(chats);
, want able see same chats content when on same page.
javascript runs in user's browser. data in variable visible client.
in order synchronize data between clients, need use websockets. each client (user) send data server , server relay client activity each client.
a popular javascript websockets library socket.io. you'll find plethora of "how create simple chat in javascript websockets" tutorials if start searching them.
here's socket.io chat demo that's right on there site.
"why use websockets instead of ajax?"
well, think little bit... ajax great clients sending data server asynchronously, server talking client?
if user writes "hello", can send server using ajax, how users b , c notified new message arrived?
historically, before websockets, done ajax "long polling". means each client make ajax request server every x seconds asks "hey, new messages me read?"
if you're implementing realtime chat app, means x going max of 5
seconds otherwise users frustrated lag.
pinging our server every 5 seconds ask same question on , on annoying. , it's quite archaic today's standards. maybe there's better way...
"ok, how websockets make better?"
well websockets allows connection between client , server stay open. means server can send data client data arrives, without client having ask it.
this means can ditch polling and data sync'd faster! sweet!
"ok, that's great, can't rely on bleeding edge technologies..."
well that's not problem either. reason recommended websocket lib (e.g., socket.io) because socket.io make wide variety of attempts achieve socket-like connection in event browser doesn't support actual websockets.
included in list of fallback methods none other than... drumroll, please... ajax long polling.
"is there alternative socket.io?"
yep. know you're looking should easy find tons of options out there. ws great lib i'd check out if socket.io seems heavy-handed you.
Comments
Post a Comment