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.
Related
I have the following problem: I want to change one variable on a page. The input comes from another page so:
I'm using Node.js, Express.js and Ejs for this task.
Server - storing the values
Index page - Control page with input fields and send button
Display page - Shows the variable
I'm sending the variable with fetch post to the server. On the server I change the variable with the request body value and when I reload the "Display page" manually I see the new value. The problem is: I need to change it without any manual refresh or other things, because that won't be possible.
There is the possibility with "location.reload()" to refresh it every X second. But that's not the way I want to use, I really just want to refresh it when the variable changes. Is there a function (from express.js for example) I can use for it?
edit: I should mention that this project would be just used in our network and its not open for other users. Like an in-house company dashboard kind of.
So a "quick and dirty" solution can work too, but I want to learn something and wanted to do it the right way though.
This is a very common scenario that has several solutions:
Polling - The display page runs ajax calls in a loop every N seconds asking the server for the lastest version of the variable. This is simple to implement, is very common, and perfectly acceptable. However, it is a little outdated, and there are more modern and efficient methods. I suggest you try this first, and move on to others only as needed.
WebSockets - WebSockets maintain a connection between the client and server. This allows the server to send messages to the client application if/when needed. These are a little more complex to setup than just plain ajax calls, but if you have a lot of messages getting sent back and forth they are much more efficient.
WebRTC - This is taking it to another level, and is certainly overkill for your use case. WebRTC allows direct messaging between clients. It is more complicated to configure than WebSockets and is primarily intended for streaming audio or video between clients. It can however send simple text messages as well. Technically, if you want to persist the message on the server, then this is not suitable at all, but it's worth a mention to give a complete picture of what's available.
The simplest solution that came to mind is to have the server return the updated post in the body, then use that to update the page.
You can also read about long/short polling and Websockets.
One possible solution would be to add page reload code after a successful post-operation with fetch.
fetch(url, {
method: 'post',
body: body
}).then(function(response) {
return response.json();
}).then((data) => {
// refresh page here
window.location.replace(url);
});
Proper solution (WebSockets):
Add WebSocket server as a part of your Node.JS app
Implement subscriptions for the WebSocket, implement function 'state changed'.
subscribe on a method 'state changed' from your client browser app.
call ws server from your express app to update the clients when your variable is changed
Outdated (Polling):
Add express endpoint route: 'variable-state' Call server from your
client every n ms and check whether variable state is changed.
Refresh the page if variable is changed.
Hey I have been looking around for like 2 hours now and cant really find what I'm looking for. I want to turn a JavaScript variable into a server-side variable so that when it is changed it is changed for everyone visiting the site. I have tried looking at Node JS, XML, PHP and SQL but i have absolutely no clue which one is the one I need to do this. If any of you guys could give me something to research in order to accomplish this I would be grateful.
My code is a voting function that just increments a variable by 1 and I want it to stay as that variable when refreshed and visited by others.
JS:
/*global*/ buttonText = "Global Clicks: 0";
/*global*/ amountOfvotes = 0;
function addVote() {
var newButtonText = buttonText.replace("0", amountOfvotes++);
document.getElementById('global-respects').innerHTML = newButtonText;
}
Thanks!
There are a lot of solutions that you can use for your problem. The first two things which are in my mind are a (1) classic client-server communication, and (2) the usage of web sockets. Well, I am not so firm in the usage of web sockets, so I describe the "easier" client-server communication.
An information before I start: The tools and programming languages are mostly independent. However, you can use JavaScript on the client and PHP on the server side for example.
The first, you need, is a (e.g. JavaScript) variable on your client. You had called it amountOfVotes (cf. the picture at the end). There are two things happen during the client is active: (1) if the client add a vote it has to send it to the server; (2) all clients have to stay up-to-date.
If the Add Vote button is clicked, then you send a message (e.g. via Ajax) to your server application. Then, the server takes its current amountOfVotes, adds one vote, and stores it (e.g., in a file or mysql database).
Your clients need an intervalled function. This function sends (e.g., via Ajax) a message to the server to get the current amountOfVotes. The server's responds with the current number and the client is up-to-date.
I've developed the front-end of a web site using JavaScript.
I have a button that when it's clicked retrieves an integer value from another object on the website.
I have a local SQL database. How do I make SQL calls when this button is clicked?
I've seen answers with JavaScript/Ajax and PHP, but I don't want to use PHP.
Using JavaScript only, can I open a local SQL db and make SQL calls? If yes, how?
If I can't do this using JavaScript only, can I use JavaScript/Ajax and Python? If yes, please post a reference or simple example.
Technically it is possible to connect to a database using client-side JavaScript. However, as others have already pointed out, doing so is considered to be really bad practice for a few reasons - the most important of them being security.
When the browser is asked to load a certain page it will go ahead and ask the server for the content that is found at that URL. This means HTML files, external JavaScript files, images, stylesheets and other resources that are needed in order for the page to get rendered. Since the user has access to the these files, especially your JavaScript code, it means he has access to your database credentials. You could try to minify/obfuscate the code, but that won't make it any safer.
If you do understand all the consequences and for some reason you still want to do it, take a look at this example.
The best way to go at it is to have a server handle the interaction with the database. Depending on your language of choice, you could build that part of the application using PHP (among with an HTTP server such as Apache), Java, Python and so on. You could even use JavaScript (see Node.js).
Since you asked for a Python snippet, here's one that connects to a MySQL database and creates an HTTP server that listens for connections on port 8080. For each GET request it will receive, the script will query the database and send back the result as text/html.
#!/usr/bin/python
import MySQLdb
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
PORT_NUMBER = 8080
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method
data = cursor.fetchone()
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(data)
return
try:
db = MySQLdb.connect(host="localhost", user="root", passwd="yourpwd", db="pw_exam")
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
You can't do this from the javascript in the browser for a simple reason - if your database is available to your javascript code, it is also available for any web site user. And someone will just delete all your data or will replace it with something funny.
That is why we usually also have the server-side application and it can basically be in any language - php, python or javascript.
And there are frameworks and libraries to simplify your job also for any language.
For example, for python you can use flask and sqlalchemy.
If you want javascript everywhere, then use nodejs on the server and expressjs as server-side framework is one of most popular options for node. And you can find node.js packages to make SQL queries to your database too.
The general flow of your application can look like this:
Your client-side application is opened in the browser and it needs some data from the database
It sends the AJAX request to the sever
Server makes a database request and returns the data as json
Client-side application displays this data
It works similar when data need to be modified.
The difference here is that your database is "covered" by server side, so you can be sure that only allowed operations are performed.
Like nobody is able to drop the database, or only a registered user can edit the profile data (and only own profile data editing is possible), etc.
JQuery is a brilliant way to create live Database feeds in Website development. You can simple import the JavaScript files from CDN or Google or download and use it here: https://jquery.com
Front end:
$(document).ready(function(){
$("#idHere").click(function(){
var testdata = document.getElementByID("#idHere").value;
var anothertestdata = document.getElementByID("#idHere").value;
$.ajax({
url: "/inc/Database.php",
data: {
example: testdata,
anotherexample: anothertestdata
},
success: function( data ) {
$( "#idHere" ).html( "<strong>" + data + "</strong> " );
}
});
});
});
PHP file:
if(isset($_GET['testdata'])):
$db = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
$query = "SELECT * FROM TABLE";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)):
echo $row['CollumnName'];
endwhile;
$db->close();
endif;
Anything echo'd will show in the response.
Using JavaScript to open a Database is hard, long and has MANY security issues. I would not recommend in doing so.
I created a tabulation system for beauty pageants that show judges score on a projector. I created a presentation page for that using Codeigniter.
The HTML from that presentation page is purely written in Javascript. The page refreshes each second to get real-time data sent by the judges.
The not-so-cool thing about this logic is that when the page writes a lot of data, the page blinks every second. So the refreshing of the page is noticeable and somewhat disturbing.
This is a snippet of the code I'm working on.
$(document).ready(function() {
getJudgesScore();
setInterval(function(){
if (getNumFinalists() == 0)
getJudgesScore();
else {
window.open ('presentationFinalists','_self',false)
}
},1000);
});
You can imagine how much data is being sent and received every time this code is executed.
To sum this up, what I want to accomplish is instead of the client asking for data every second, the server initiates the connection every time a new data is saved to the database. Thank you for taking your time reading my concern.
This might help you to take necessary data from mysql server and send to client page.
Timer jquery run for after perticular time of interval.
<script src="../JS/Timer/jquery.timer.js"></script>
var timer = $u.timer(function() {
getJudgesScore();
});
timer.set({time: 1000, autostart: true});
refer this link also
https://code.google.com/p/jquery-timer/source/browse/trunk/jquery.timer.js?r=12
What you are attempting is a tricky -- but not impossible -- proposition.
#Chelsea is right -- the server can't genuinely initiate a connection to the client -- but there are several technologies that can emulate that functionality, using client connections that are held open for future events.
Those that come to mind are EventSource, Web Sockets, and long polling... all of which have various advantages and disadvantages. There's not one "correct" answer, but Google (and Stack Overflow) are your friends.
Of course, by "server," above, I'm referring to the web server, not the database. The web server would need to notify the appropriate clients of data changes as it posts them to the database.
To get real-time notification of events from the MySQL server itself (delivered to the web server) is also possible, but requires access to and decoding of the replication event stream, which is a complicated proposition. The discovered events would then need to result in an action by the web server to notify the listening clients over the already-established connections using one of the mechanisms above.
You could also continue to poll the server from the browser, but use only exchange enough data via ajax to update what you need. If you included some kind of indicator in your refresh requests, such as a timestamp you received in the prior update, or some kind of monotonic global version ID such as the MySQL UUID_SHORT() function generates, you could send a very lightweight 204 No Content response to the client, indicating that the browser did not need to update anything.
Ok so I am trying to make a program that allows teachers to edit/design a test and for students to take it. I made dropdown menues to select type of question and the category (history, english, etc.) and have textboxes to receive the question text. My question though is how to save this text and selections permanently. My initial thought was to change the contents of a js file variable, but javascript is client side. What is the easiest option as I need this quickly? Please just plain javascript/html, no jquery or jfiddle. Please explain in simple words :). I am no pro. PHP is ok but I do not know it so I will need it to be clear. If you could help, that would be fantastic as I and another guy have not found a simple solution ( at least to our minds).
If your users only use modern browsers (very unlikely), you can use local storage:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML=localStorage.getItem("lastname");
Otherwise learn AJAX. It allows to save/read data from a server async. That means you don't have to change the page and you can save your data on every selection change.
And if you want to have it easy, use a Framework. Because this is a ajax request without a framework:
var xhr=new XMLHttpRequest(); // Initialize the Ajax request
xhr.open('get', 'send-ajax-data.php');
xhr.onreadystatechange=function(){ // Track the state changes of the request
if(xhr.readyState === 4){ // Ready state 4 means the request is done
if(xhr.status === 200){ // 200 is a successful return
}
}
}
xhr.send(null); // Send the request to send-ajax-data.php
And this is a ajax request with a framework (jquery):
$.get( "send-ajax-data.php", function( data ) {
});
You can use the above answer, and send your data using ajax call.
or
you can save your data in xml file in client side.
var newXml = "text to be saved"; // your data is here (form the xml).
//Sets the data in a hyperlink for download.
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(newXml))
.attr('download', 'autounattended.xml');
or you can save the data in json too.
//creates javascript object
var sampledata = {'PkId' : 123, 'Name':'sudhansu' };
//Converts the object to json string.
var dataTobeSaved = JSON.stringify(sampledata);
then you can save this data to a file using the above method.
No matter how you slice it, there are a few things that you will need to learn in order to make this work. So instead of handing you code that you might not understand or be able to implement, I think you would be better served by some references and a simple explanation.
First, you will need to implement a CGI (common gateway interface). CGI can be implemented via Perl, PHP, Python, JavaScript (with nodejs). There are other languages that can be used, but these are the most common.
After you have a CGI script setup on your server, your client-side application can submit data to the server via a AJAX request or via a HTML Form submit. Most people use AJAX, but both options work.
Once the data is sent from the client and handled by the CGI script, you will want to be able to interface with the data. CRUD is an acronym for interfacing with data, it stands for Create, Read, Update, Delete. While it is possible to implement this by storing the data in a raw text file, it is generally considered a bad practice. Thus I would recommend that you look into using some type of SQL database, MySQL, PostgreSQL, SQLite are a few that are relatively easy to implement (SQLite being the easiest of the three imo).