Creating a real-time chat with php and javascript - javascript

My goal is to create a real-time chat similar to the Facebook chat, from scratch. I want to store all the messages on a database table (MySQL) and every time a new message is sent by a user, if the receiver is connected then a request will be sent to the receiver's browser and the message will appear on the chat window.
I don't want to have the client to check if a new message for the user was sent, but I want the server to send the request to the client's browser.
I know that this can be achieved using the Comet technique (I saw this stackoverflow question) but I am not able to find a good guide on how to implement this for this certain problem.
I want to use php and javascript and as less extra software or frameworks as possible.
I use WAMPServer and I have Windows.
If you know a good guide or tutorial or can provide any guidelines on how I could achieve what I want, it would be very helpful.

Try use for this CppComet open source comet server. There have api for php and other languages.
And viwe this chat example or this

You can also use Node.JS with PHP. Creating a Real-Time Chat App with PHP and Node.js

I have already developed an application which is not completely Real-time messaging system, but it works like realtime. Built using without any external new frameworks/API, just used known and familiar skills to develop this using: Ajax jquery, PHP, Mysql, Javascript.
Logic used is:
All messages will be stored in database,
When you load page all messages will be loaded from database.
When you get new messages after reloading, the new messages has to be
loaded/displayed without reloading whole page again right? This is done
using javaScript and ajax jquery. I have set time out for EVERY 0.5 seconds
to reload only new messages and display them.
In my code, At first when the page loads all messages will be loaded in div
tags each, Later whenever new message gets into db it will displayed into new
div tags. its Simple and works without any external API.
To refresh new messages and throw them in to div tags .load() from ajax jquery is used,
to refresh every 0.5secs Javascript is used to set timeout.

I don't know what your exact question is but Websockets is the answer!
https://github.com/crossbario/autobahn-js
https://github.com/voryx/Thruway
(FYI, when you see WAMP in the context of websockets they're talking about something that's not windows/apache/mysql/php)

Unfortunately you can't make a real time application with PHP it self you can use a framework like Laravel in PHP and use packages like laravel-websockets and create a realtime application. laravel-websockets is really useful for creating a realtime application. laravel and the laravel websokcets with any front end you can do this
http://beyondco.de/docs/laravel-websockets
https://laravel.com/docs/
You can easy create anything with it just try to understand the fundamental concept of websokcets .

Related

Node.js - Proper way to add same block of code on event

I use Node.Js along with Express and Express HBS (Handlebars). And for users real time synchronization I use Socket.IO.
Let's say I code a web chat and each time someone hit the send message button I emit an event from client to the server. Next, the server will receive this event and emit a new event to all the others client, updating everyone one with the last message send by our first user.
Since we all want to be messy for the less and organize as possible, I would like to have a template file containing my new message skeleton. But after that I don't understand what I've to do. My first thought was render this template either :
from the client with data send by Socket.IO.
or from the server and send back the html rendered to the client through Socket.IO.
But it seems that's not recommendable ways, as far as I am in my research.
What I would like to avoid is :
HTML Skeleton inline in the client JS code receiving the new message from Socket.IO.
that everyone ask to the server (ajax request for example) the same message just after receiving the info from Socket.IO that it is one available. What if I had 10,000 users sending and receiving message ?
that we put the block of code in a <script></script>, get it inside the js and put it at the right place in the DOM when I need it. Best approach I found for the moment, but what if I need a lot of this sort of thing ? I don't like the idea that I could have a lot of blocks code at the end of my DOM just in case I could grab it and use it, maybe or maybe not.
Reload the entire page each time a message is send.
Actually, my current project is not a chat but I use this as an example. Keep in mind that the block of code I want to add to the DOM on events could be more heavy than just a chat message.
What is your thoughts about all of this ?
What you can do is send the template earlier on as a string, compile it and store as template (in some Map). Then when a new message comes in, you just need to pass in the data to get the html content where you can then set as innerHtml to some div at your desired location.
If you need my thoughts i will say the stack may be an issue. You want to realise a reactive feeling in your application but at the expense of your api, as it continously compile those templates to send to your various clients as html.
Another bad effect to consider is those html tend to be heavy when sending to the various clients, whereares sending just the data that changed is quite light weight.
Best approach will be use a client framework that is best suited for such reactivity you need. A library/framework like React will permit you manage the events, and show new data using components available on the client. You will only need to send data concerning the event like the sender info and content.
Check out this page on handlebars website specify best suits for handlebars. https://handlebarsjs.com/installation/when-to-use-handlebars.html

Sending safely JSON to server via an HTML form page

I have an html page that has a form and is communicating to a server via JSON requests, when loading (e.g. in order to remember user's previous answers) and when submit button is pressed (e.g. in order to save his new answers). Every user has a specific user_id that is located as an attribute in the url of the website. I have only HTML pages, CSS and Javascript that makes some simple functions, as well as received and sends the requests.
The problem is that the server needs an api-key for the request to happen, that I need to be kept hidden, but instead is easily discovered when the user sees the source code. I want this specific line to be hidden, but I guess this is not possible without any backend in the game.
I would like to know the easiest and fastest way to get from this state (just frontend, where every piece of information in the source code is totally insecure) to another where the api-key (at least) is not on the open.
I guess the solution is to use a server for that part but I need suggestion on the easiest transition from my code to another. I tried to use GWT, as I am a bit more familiar with JAVA backend application (but not with GWT), but seems like a big trouble, where I need to change my HTML, my Javascript and also the CSS that I have may not be useful, as well as I face a lot of problems when trying to read my parameters.
I know that it is not the best way but I do not have a lot of time to make it work, so sorry if it seems lazy (I am new to this type of programming), but I haven't found anything helpful and I cannot study for 2 weeks in order to be able to begin implementing it.
Is node.js (which is Javascript and I already have implemented the request sending/receiving in this language) easier than GWT for that matter? Will my sensitive data be secure in that way? I would be grateful if there was a similar sample, that I could start using for my implementation, as I haven't find anything that is specifically helpful for my situation.
Thanks in advance!
NodeJs is not javascript, NodeJs is specific javascript "interpreter" whose is purpose is mainly to be executed server-side. If you have an HTML page, it is likely to be loaded in a web browser (client-side), so not in a NodeJs environnement.
Everything that is hard-coded in the javascript of you web page is visible from the client, there is no way around that. So yes, you need some server-ish thing somewhere.
If you are not to manage a server by yourself or via PaaS, you can go for a serverless architecture. For instance, If you consider AWS which I know the most, you can easilly add some user management to your web page using Aws Cognito User Pool. Once a user is connected and have the good permission, he can be granted access to some other resources via a JWT token that you send along with your request.

Facebook Login - JavaScript or PHP SDK

I am at the stage where I am thinking of integrating a social login method into my site. Of course my first one will be the facebook login before moving onwards.
Basically my question is : Which language is best for this type of OAuth connection, and which is going to let me do everything I want?
This will encompass all OAuth connections in general eventually, but specifically Facebook for now.
From what I have read of the documentation, the JavaScript SDK allows you to login, and connect to the open graph API - which in turn will allow me to post / upload etc etc. This is also available in PHP.
From experience which is the more durable route to go?
PHP or JAVASCRIPT
The best and recommend way to authorize users is the JavaScript SDK (FB.login). No redirect needed (better usability), very easy to handle, no PHP needed (the new PHP SDK needs PHP 5.4+). Use PHP only for stuff that involves usage of the App Secret or Extended Access Tokens. And for cron jobs, obviously. You can even just forget about the PHP SDK and use your own CURL calls.
Btw, security is no problem, you should just activate "appsecret_proof" in the App Settings.
More information about appsecret_proof:
https://developers.facebook.com/docs/graph-api/securing-requests
http://www.devils-heaven.com/facebook-php-sdk-4-0-tutorial/
One more reason (and one of the most important ones) is the possibility to refresh Access Tokens (=User Sessions) easily without page refresh by using FB.getLoginStatus.
And another reason is that you need to upgrade to new PHP SDK versions on your own. The JavaScript SDK does not need any upgrades, in the lase few years you only had to change one or two parameters in some cases, the SDK gets downloaded from the Facebook servers.
Also, if you add Social Plugins, you need the JavaScript SDK anyway.
TL;DR PHP/both
I'd really recommend PHP. You'll want to store the login in database. If you do it via JS, you'll need to make an Ajax call to the server, which is not really that secure.
Having said that, they are targeted for different uses. JS is for frontend more, while PHP is for backend (db storage, checks, actual site login, etc). Using JS will let you generate the buttons on the fly, while using PHP you'll need to do some more coding.
Somehting else, the php library will get updated from time to time and you'll need to keep up after testing. JS also, but it's easier, since the code usually works.
If you only want one, use PHP. You can control what the code does and JS will not break your site since it's written by you. However, I'd recommend using both since you will probably want more than just simple login
Edit:
As facebook states, use PHP SDK: Usually this means you're developing with PHP for a Facebook Canvas app, building your own website, or adding server-side functionality to an app that already uses the Facebook SDK for JavaScript.
https://developers.facebook.com/docs/reference/php/4.0.0
The best route would be to use both, together. Some users might have javascript disabled or you might do something within your javascript code that will not work on some browsers. So as a fallback method you can use php api.
Going with only php would be solid and will work regardless of what the users client is, but you can make the user experience better with javascript.
Still, in most cases you'll end up having to use both.
I have just spent the afternoon playing with the JavaScript SDK for facebook and I have to admit I think this is going to be the best option for what I need.
If anyone else is reading this, it may not be perfect for you - but with the way my application has been built I think it is a perfect fit. Here is why :
My standard login system uses JavaScript to grab my form data, then validate, which then passes the validated data via AJAX to a PHP validation script. Which in turn returns a JSON response to the original AJAX call. If my call comes back with "ok" : true then we are good to go basically.
The way the facebook JavaScript SDK works is almost a perfect little jigsaw puzzle to bolt onto the system I am using. All I require is a little bit of profile data, to then keep a record of this user on my system. THIS is provided by facebook, then validated by myself.
However, other social network logins may not be as nice and simple to use as the facebook API, so I could end up changing my mind on the overall system. For now just using facebook, I think the JavaScript SDK is absolutely spot on, as it just gets the information for you to run through your own validation on site. As I said this is a perfect fit for my system however it may not be for yours.

Twitter like new tweet count notification in ASP.Net

I have very limited knowledge in jQuery. I need to develop a page which should show the count of new message posted. In twitter and stackoverflow websites, I have seen a div which shows the count of new tweet/questions posted and while clicking on it, the newer ones are shown on the top. Below added are the sample images:
Please suggest whether it can be attained using jQuery or Ajax.
Thanks
Those examples look like push rather than pull behaviors. By this I mean that the server is saying to the page 'hey there is a new tweet in this tag' rather than the page asking 'is there any new tweet? No not yet? OK, I'll ask again in 5sec'.
Since you are on ASP.NET, you can easily push notifications from server to client by using the good SignalR library.
You still have to detect on the server that there are new 'things' and send a message (with signalR) to the matching clients. And also handle the message on the client and show a piece of UI.
As you are using ASP.NET, you can use an UpdatePanel to help handle making the call and updating your content. Note that the UpdatePanel uses AJAX, and can be set to automatically update on a specified time interval.
What I would do, if I were you, is use the UpdatePanel to call a method that makes a request to the Twitter API and grabs all of the new tweets that you have not already grabbed. Then count the number of tweets returned and, if that number is greater than zero, I would display the "X tweets with new activity", or whatever counter message you are looking to show.
If you are not strong with jQuery, this may be the best solution for you, as you could get away with using the UpdatePanel and a Repeater to render out your tweets, and update the ones displayed when clicking a button/link/etc, with or without postback (whichever is your preference for this implementation).
Important Side-Note
Note that Twitter API v1.1 requires you to use oAuth Tokens, which should not be included in AJAX calls. You should only be using server-side code to make requests to the Twitter API, and, thus, this solution is likely to be the best for you, as you can write your request code in the code-behind (thus keeping your Twitter keys and tokens safe), and call it using the UpdatePanel.
Update
I am not usually one to promote my own libraries on Stack, but if you need help with making the request to Twitter's API using oAuth, take a look at my C# library for Twitter requests. The documentation includes instructions for setting up oAuth access on Twitter and is very verbose in helping you make calls with the library. It also includes MSDN-style documentation for the library, itself, an example request, and full IntelliSense for all classes, methods, and properties. If nothing else, it should help you set up your requests. If you have any trouble with it, let me know and I can help you out.
You need to retrieve the new messages using a $.ajax call which you repeat every few minutes or so using setTimeout. But for that ajax call to work you have to have some sort of API endpoint you can retrieve the data from.
This is not just something you can build by dropping in a jQuery plugin somewhere and be done with it. You need to have knowledge about Javascript, jQuery and your specific API before you can do anything. Try checking out the jQuery basic tutoorial.
You can create a WCF service to get latest messages which you can call using setTimeout to update your message div in real time using Ajax or you can use SignalR to add real time functionality.

How can I create a chat application in PHP/Javascript?

I'm trying to create a chat system using PHP and javascript. I want to know how the chat in Gmail works: it will remain in the same position even as the user moves to another page. I would be grateful if anyone could explain how it works.
And at the same time, please give some ideas on how to create a chat s/m. For example, the creation of the popup window, protocols to be used with chat, etc.
The chats in GMail, Facebook or Orkut stay at their same position even when you change pages thats because they are not doing a real page change when you click on any link inside GMail or Facebook or orkut. They load the page by means of a hash tag identifier and load the contents using standard AJAX. For example inside GMail you would find all links like inbox as https://mail.google.com/mail/?zx=xxxxxxx&shva=1#inbox and https://mail.google.com/mail/?zx=xxxxxxxx&shva=1#starred so when you click on them the browser doesn't actually reload a new page instead makes an AJAX request and pulls data in, hence this doesn't affect the chat block on the page.
You can have a look at http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=9#start for a simple PHP/MySQL based chat application. If you want a scalable chat application you have to go in Comet or "Bidirectional-streams Over Synchronous HTTP" BOSH. Friendfeeds TornadoWeb in python can help. http://www.tornadoweb.org/
Hope this info helps.
I understand that you want to create a "Chat system",
Gmail's chat is not an isolated system, it is closely integrated/Synced with Gtalk ,
(do you plan on providing a Desktop app as well as a web interface?)
Secondly Gtalk/Gmail chat uses a custom protocol(although it is open..meaning you can write your own Gtalk clients as well).
For your "Chat System", if you want it to be as nice as Gmail's you'll definitely need to use
AJAX and JSON along with Java Script and PHP
AJAX will help you to create Eye Catching at the same time responsive UI and and JSON will help you to transport data along the wire.

Categories