I am using socket.io to create a party game similar to cards against humanity. I am just wondering how I can keep the players name and score etc without having to send all the data to a new page when new games begin. I was thinking to just change the body of the html but stay on the same page so the javascript doesnt reset and I can still access all the players information.
I came across using document.write() however this appears to only accept a string parameter. Is there a way to do something like this document.write(game.html).
Any ideas on how to go about this, maybe a better way to pass information between javascript files without having to post the data each time a new page is loaded? I have tried sending the data with post however it makes it far more difficult to keep everything consistent.
P.S This is the first time I have properly made anything with node.js, socket.io, javascript etc. So I could be asking a stupid question.
Once you get socket.io data from an event listener, you can use querySelector() or any other DOM manipulation method to show the data in the DOM. Something like this?
HTML
<div id="panel"></div>
JS
const socket = io("ws://localhost:3000" )
const panel = document.querySelector("#panel")
// receive a message from the server
socket.on( "hello", (arg) => {
panel.innerText = arg
});
Related
I am developing a query PHP enabled chat, currently am using ajax to pull data from the server and display it in the chatbox but this makes use of multiple ajax requests to the client computer which causes it to slow abit....
This is what I am doing using ajax and yii2
function getdata() {
$.get("controller/action").
done(function(){
//process json
$("#chatbox").html(data);
})
}
then am using
windows.setInterval(getdata(),1000);
Are there better ways to fetch this son data without using ajax and jquery
I have checked on This link buts its not very helpful
You can use socket.io or websockets api which is an alternate option to ajax, So, by using socket.io, jquery, php OR nodejs one can build one to one private chat without using ajax, following links will help you out how to build private chat.
socket.io
WebSockets
Private chat reference 1
Private chat reference 2
A better approach is using nodejs instead of php. You can check this link for a really nice implementation of chat which you can use.
While php chat has performance issues like you mentioned, nodejs doesn't because instead of polling the messages it pushes them to the client when there is something to push. And also you receive ready to use solution right out of the box (of course you have to modify it) which will save you development time.
But if you still want to go with the php way, then you have these options:
jquery + ajax (like you are doing it right now)
php sockets - here is an example of php chat using websockets https://www.sanwebe.com/2013/05/chat-using-websocket-php-socket. This approach has its pros and cons. One of the major cons is that is not supported by old browsers and may be the setup process is not that easy. But I'll prefer it over the ajax requests.
You mention getting data from the database, but one could argue that, for the purpose of a chat application, the database is incidental. Maybe you want to store the chat history and the database is a natural place to do so, but the primary functionality is to transmit messages. So you are using the database as some kind of message buffer.
Websockets seems the best option, as others have mentioned. If you want PHP server-side, in addition to the Kraken framework as mentioned in a comment to your question, you can take a look at the Ratchet library. They have a tutorial for a simple chat in their site: http://socketo.me/docs/hello-world
Basically, you need another server-side process (in addition to your webserver) to receive and broadcast the chat messages. Following that tutorial, in the onMessage method of the Chat class you can do the insert in the database if needed, preferably asynchronously.
Client-side, you will need to connect to the websocket using Javascript. Simple example:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log('Message received: ' + e.data);
addMessageToChatbox(e.data);
};
$('#yourChatInput').keypress(function(e) {
if(e.which == 13) { // "enter" was pressed
conn.send($(this).val());
$(this).val('');
}
});
function addMessageToChatbox(message) {
//
}
You can do a trick, suppose data is not json it is javascript file declaring single variable now you have to add it to document such as
below is your data.php(javascript generated by php)
in php
echo 'var x = {"name":"Anshuman"}'
In javascript
var s = document.createElement( 'script' );
s.setAttribute( 'src', 'data.php');
s.onload=callback;
document.body.appendChild( s );
function callback(){
console.log(x);
}
There aren't any sensible ways. You have to bring the new data in somehow right?
The to ways to do that are by reloading the page or by Javascript / Ajax to avoid the reload.
You could make the update one sided so that when Person A writes to person B the request is performed on the submit of the new message. This would mean that no new messages are retrieved unless one is sent. (Not practical)
Another method would be to have a last message time noted somewhere on its own and you could repeatedly check for that.
Should that time change you could fetch new data then but that would not fix the amount of requests... only the amount of data being transferred.
I suggest you look at the size of the data from the json/php. Have you ran tests to see how long that is taking or how it is performing?
I could refer you to this post which is using NON jquery requests if you like.
I've just recently discovered slack.com and I fell in love with the way they handle their interface. If you've never used it before it's quite easy:
There is a side navbar and an main container on the right. Everytime you click an item in the side navbar it's content is loaded in the container. The focused item changes, the container's content changes, but the page doesn't reload.
If the data changes in the meantime it is magically updated.
What would it take to achieve something like that?
URL changing, page not reloading
Content always up to date
I've been looking at meteorjs in the past few days but the url part is never mentionned.
Yes. Slack is awesome. We (My team) use it everyday. I use it so regularly, at some point I don't check email but I check slack.
So, up to your question.
URL changing, page not reloading
It can be easily done by javascript [ Tl;dr ]
Code:
window.history.pushState("object or string", "Title", "/new-url");
Content always up to date
Well this can be done in two way,
i. via Ajax and Javascript
ii. via socket
i. via Ajax and Javascript:
in javascript you can make setTimeout function to fire ajax request in some duration. via Ajax it will get newest message from backend and it will be shown.
ii. via socket:
in socket, in your case if you use node.js there is a very popular library named socket.io which will get and update message in real time.
Good luck!
You need Ajax. You can use it in conjunction with a script, probably PHP that checks the state of the databse over a timer interval (a "heartbeat") and if anything has changed you load in the new data. I'd recommend having a specific column for a datetimestamp to compare with to make the smallest possible load on your database from this as a lot of users being on the page at the same time will make a lot of requests.
For the "url changing feature but no reload", I think #Kavan Pancholi answered your question. Another way to achieve that is by using the yield templates feature of iron-router.
You are using meteor, it means that you can do it without too much trouble (forget about Ajax & Sockets).
I don't know Slack (but I'll definitely have a look at it) but from what I understand, all data is preloaded/lazy loaded and they only change the displayed elements. In other terms, you keep ready and loaded all your client subscriptions or you bring them up when your yield template is loaded.
I will have a look at Slack and edit this if I realize I did not understood correctly what you are aiming for.
Edit Ok I tried it. You need to use yield templates with iron-router and they also added some transitions effect you can achieve with _uihooks + a loading template
On top of that, if you use a framework like angular, you'll notice urls like this:
http://localhost:3000/#/chat/room
You've probably seen similar with wikipedia in having urls like this:
https://en.wikipedia.org/wiki/Cat#Cats_and_humans
That little # won't reload the page on the url, so you can use that to make a url routing action without changing the page. You can access it with window.location.hash. So on the wikipedia article, you'd get
> window.location.hash
#Cats_and_humans
Combine that with ajax and event listeners and you can do something similar.
// using jquery
// set a callback when the hash changes
$(window).on('hashchange', function (e) {
e.preventDefault();
var hash = window.location.hash;
// get your container where you want to add data and clear it out
var $container = $('#container');
$container.html('<ul></ul>');
if (hash === '#/movies') {
// request json from an endpoint, and with the data, append it to the dom
$.getJSON('/api/movies', function (data) {
data.each(function (el) {
$container.append('<li>' + el.name + '</li>');
});
});
}
});
I'm trying to create an auction tool using PHP. The problem I'm having (and I appreciate its a basic one but I need clarification) is that I don't understand how to update the "auction price" automatically on each users screen without them having to take any action or without causing a full reload of the page.
So far I understand that Ajax is used to do this but if anyone could point me in the right direction or to any useful materials. My plan for my project so far is to use PHP and JavaScript so any solution would need to be compatible with these languages.
Note: I'm using a MySQL database.
Ther question you asked has so much possible answers, they could fill a whole book.
The simplest way to do this is to make an ajax call every few seconds using a combination of the setInterval() function and AJAX calls. You basically make an AJAX request every few seconds:
setInterval(function(){
$.get( "anyChanges.php", function( data ) {
//do something with the returned data. Maybe update a table or something
});
}, 3000);
On server side anyChanges.php returns some data immediately, like confirmation that something has changed and the new data.
Long polling is how Google and others do it. It's the same as the example above. The difference is on the server side. anyChanges.php would not return immediately, the script would keep the connection open until there is some new changes and return them. If you use long polling, you usually set the interval to longer, for example 30 seconds.
The best way to do it in my opinion, are WEB Sockets. It is a very new technology. With web sockets you can create a two-way connection to the server. That means that the server could simply send data to the clients without them having to ask for new data every few seconds. In PHP it's a little difficult to use web sockets (Or so I heard), but you could give it a shot. If you choose web sockets, try to learn about them first:
tutsplus tutorial
This library will be helpfull:
socketo.me
Php/Ajax example:
In this example you have index.html and record_count.php files
Here is the Code:
index.html contains the html code and javascript call to load record_count.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<body>
<div id="load_tweets"> </div>
</body>
and record_count.php has the php code
<?php
echo "some code or variable here";
?>
you can change the javascript interval to suit your needs
I'll leave you the blog link as a reference: 9lessons
As I making interactive displays, which must switch pages instantly, then I create pages without refreshing.
My approach is something like that:
I have one index.html with all structure (pages) with all necessary html tags.
javascript/typescript loads json from CMS (Kirby for example), which has all information about texts and image links.
when json is loaded now I just need to switch between pages by showing/hiding or creating/removing html elements. And all data and texts are loaded by javascript.
There is some cons, which can be fixed, for example link for each page in address bar. In that case You need to add history management and change url in address bar on page switch.
Let's suppose I have a script that needs to log something on the server. I have an endpoint like http://myServer.com/recordLog and I can hit that with some parameters and it'll make a record. Some caveats:
I can control what the server returns
This will happen millions of times per day.
Efficiency is of utmost importance.
The script might be loaded from another server and within an iframe, so browser security issues are in play.
I dont really care about the response at all. Even if there's a communication failure, I'm not going to do anything about it.
I can't do anything that affects the state of the rest of the page.
My first thought was to make an ajax call -- it seems like the "modern", "right" way to do it. However, in some circumstances, that can trigger cross-domain security issues.
My other idea is to load a 1x1 pixel image or an empty <script> into memory. Something like:
var i = new Image;
i.src = "http://myserver.com/recordLog?foo=bar&baz=buz"; // returns 1x1 gif
or:
// this is similar to ajax-p, I suppose
var s = document.createElement('script');
s.type= 'text/javascript';
s.src= "http://myserver.com/recordLog?foo=bar&baz=buz"; // returns empty text file
I'm pretty sure there's no need ever to put the image or script into the DOM. Merely setting the src causes the browser to make the request.
These two are pretty similar. The general standard seems to be to use pixels, but I think that's a hold-over. I would think an empty script would be slightly smaller to transfer. Any advantages of one or the other?
Any other ideas / methods? Any hidden gotchas I'm not thinking of (such as, perhaps, ancient browsers that wouldn't work as expected)?
I don't see the problem with this:
var xhr = new XMLHttpRequest;
xhr.open( 'GET', 'http://myserver.com/recordLog?foo=bar&baz=buz' );
xhr.send();
If you want to submit a query, why not just create a form and submit it.
<iframe id=invisibleiframe ...>
<form target=invisibleiframe action=log>
<input type=hidden name=logmessage value=log>
</form>
<script>forms.log.submit()</script>
Just create an iframe and point to some logging URL that doesn't return anything.
Or you can use a NoSQL database for storing log messages, such as CouchDB or MongoDB. CouchDB for example, stores JSON documents and you interact with the server using a RESTful API. MongoDB on the other hand, stores documents in BSON format (a binary format inspired by JSON). There are a lot of examples that will get you going on their sites.
How can I capture user interaction on a website? How many links a user has clicked. From where user has come. I want to create my own logic. I don't want to use any statistics tool. How can I accomplish this?
Thanks in advance
Place where user come from you can get by referer (document.referrer).
And if you have some kind of session or mark user(by cookies), than you can check what links are clicked by capturing onclick event. But do not put onclick on every link, just use event capturing technique. In jQuery this will be:
$('a')
.livequery('click', function(event) {
alert('clicked');
return false;
});
If you want to capture what link was clicked when goes away - you should place onunload event which will send data about clicked link to your server.
There are 2 ways that I know of:
make a service, and call it using a GET method on each event you want to track.
this is something like this:
service.php?event=pageview&time=127862936&userId=70®istered=true
this way your service can work with the data.
second way that I know of, which I myself use, is calling to some dummy Image on my server, chaining GET query to it, and then analyze the request to the image at the server side. each request is anylized and logged, then I build reports.
again, you need to know what events you want to grab, they are pre-defined, and need to catch and send them as they happen. you client can put a 1-script js file, but this script need to add events listeners. lets say you want to know when the use has quit the page. add an event listener to the onbeforeunload event, like this:
window.onbeforeunload = function(){
sendStats({event:'onbeforeunload'});
}
then sendStats function breaks down the JSON and builds a query to be sent to server like this:
function sendStats(statsJSON){
var url = [];
for (var key in statsJSON) {
// make sure that the key is an actual property of an object, and doesn't come from the prototype
if( statsJSON.hasOwnProperty(key) ){
var sign = (!url[0]) ? '?' : '&';
url.push(sign);
url.push(key + '=');
url.push( encodeURI(statsJSON[key]) );
}
}
var time = new Date().getTime();
url.push('&time=');
url.push(time);
var stat = new Image();
stat.src = clientHost + 'stats.gif' + url.join('');
}
Start with web server log files, dig into it's format, try some simple stats. Then you may want to read through the code of statistic tools like awstats to enhance your vision on that.
I am a asp .net developer. But i think this technique will work all the time. If you want to find out from where user has come to your site, you can user some sort of tracking querystring variable www.mysite.com?IMFrom=something. So you when you post your link on some third party website for e.g. say Google. Post link as www.mysite.com?google=traficfromgoogle. You might have trafic comming from different otherwebsite. Have different querystring variable for each. You can also use some kind of unique id for all website which is sending trafic to you. Now create the tracking function which will track this querystring variable. Use this function where it will get called during each request.
And you can now put some customized logic for each request having such querystring.
I don't think you'll need to capture this, as it is most likely already captured in web server logs by the web server itself. You just need to find the software that can analyze the logs and give you some nice metrics. There's lots of packages out there for that.
I know its not creating your own logic but if you decide you don't want to parse your server logs you could try a new service that is trying to one up google analytics: http://mixpanel.com/. It's real time analysis and they have a free limited account so you can try it before you upgrade.
I haven't tried their api to get stuff out yet but I imagine that you could let them collect the data from your site and do some fun stuff with it after you get it back out.
Use Google analytics and hook up site elements using their API.
record and replay the web https://www.rrweb.io/
This can be useful for:
- recording user interaction/events in the browser
- sending recordings to your backend only when an error