How to display dynamically updated data in JQuery - javascript

I am trying to display how many rows are there in the database. This should be dynamically updated, so when the number of rows change, the displayed number is also updated. I tried to print it with PHP but it is not dynamic.
Here is the index file:
<script>
$(document).ready(function() {
setInterval("ajaxcall()",2000);
});
function ajaxcall() {
$.ajax({
type: "GET",
url: "count.php"
success: function(response){
json_object = JSON.parse(response)
var count = json_object.count
// HOW TO DISPLAY COUNT SO IT IS DYNAMIC
}
});
}
</script>
And here is the count.php
$num_rows = mysql_num_rows($result);
echo json_encode($num_rows);

You need to either -
Periodically make ajax calls to check for updated value.(This is what you are currently doing.) -- Usually a bad idea if users are going to be connected for very long.
Or, a better solution would be to use HTML5 web sockets instead.
Projects like socket.io make it very easy to implement websockets on a javascript server(node). But PHP also has a few options. -
Ratchet - Similar to socket.io but built for PHP.
Elephant.io - Also a PHP implementation of websockets but it is a ws 'client' which is meant to work on the server. So, you'll probably have to deploy node and socket.io on the server as well and drive it using elephant.io to handle websocket communication with the other clients.
phpsocket.io - "A server side alternative implementation of socket.io in PHP based on Workerman." - according to its github page.
There isn't much documentation on phpsocket.io but the API looks simple enough from the examples in their readme. Something like this should work for you --
<?
use PHPSocketIO\SocketIO;
// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
$socket->on('get count', function($msg)use($io){
$num_rows = mysql_num_rows($result);
$io->emit($num_rows, $msg);
});
});
and on the client--
var count = 0;
// check if browser supports websockets
if ("WebSocket" in window) {
var ws = new WebSocket("ws://yourdomain.com:2021/");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("get count");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
json_object = JSON.parse(response)
count = json_object.count
$("#database-results").text(count);
};
}
*Disclaimer -- I haven't tested the code above or used the phpsocket.io library before. So the code might not work. Also, Ratchet looks to be a more mature project so you should investigate it further if you want a more robust solution for your app.
I got a lot of the above info from this so thread. Some info there is however a few years out of date and the top rated answers there don't offer the best solutions for today.

You can update a DOM element with the count variable from the AJAX response.
Something like the following:
<span id="database-results">
</span>
Then in your AJAX success call, append the count variable to the HTML element:
success: function(response) {
json_object = JSON.parse(response)
var count = json_object.count
$("#database-results").text(count);
}
As an additional note, you would be spamming the server with AJAX requests every 2 seconds, depending on your user base this may be something to consider.

Related

Understanding Ajax requests to update page content when SQL Query Response changes

I am writing a page update which works with PHP to read a SQL database the page echo's the contents in a div section 'track_data'. yet it doesn't do this update idk
I have JavaScript script which I dont really fully understand and hopeful someone could explain its principally the check response section I think is failing ? :
in my PHP page :
<script type="text/javascript">
function InitReload() {
new Ajax.PeriodicalUpdater('track_data', 'fetch_sql.php', {
method: 'get', frequency: 60, decay: 1});
}
</script>
Thanks for looking and hopefully someone undersstands this and can put a smile on my face for the second time today :)
Steps to fix
Thanks for the suggestions of syntax errors. I haven't really got very far with this here are the changes you suggested which I have changed but I still think there is something wrong with last function as it doesn't update div section.
Code in JS file
// Start Clock refresh
// uses new new Ajax.PeriodicalUpdater(
// in main fetch file to trigger the auto update of the page.
// Written by Denise Rose
var gUpdateDiv;
var gContentURL;
var gcheckInterval;
var gcheckURL = "";
var gCurrentCheck ="";
_fetchUpdater('track_data','/fetch_sql.php','/fetch_sql.php',8000);
function _fetchUpdater(updateDiv,contentURL,checkURL,checkInterval)
{
gUpdateDiv = updateDiv;
gContentURL = contentURL;
gcheckInterval = checkInterval;
gcheckURL = checkURL;
setTimeout('check();',gCheckInterval);
}
//Called by _fetchUpdater every (n) seconds determins if content should be updated.
function check()
{
new Ajax.Request(gContentUrl,{method:'get', onSuccess:'checkResponse'});
setTimeout('check();',gCheckInterval);
}
// looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
}
}
This is the bit I dont understand
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.response.json();/*t.responseText;*/}
});
}
}
Method and Issues
What is transport here and what is t? if it stores the contents of the body text from the second in gCurrentCheck and compares to transport version content then why doesn't it update if its different please which it is if the SQL has created a different page?
I did find this https://api.jquery.com/jquery.ajaxtransport/
First Answer not using Ajax
I was given a neat and JS version as an answer, which is not really what I was looking for. I was hopeful to get the one working with one with Ajax but I appreciate your efforts is very kind. I just really wanted to send a refresh to the div area so that the PHP rebuilt the page from the SQL.
I might have been missing the MIT javascript http://www.prototypejs.org/ lol but I dont think it was.
Just to help:
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. ... Make requests to the server without reloading the page.
Researching
I found this Update div with the result of an Ajax-call but it did not really explain as the OP was using PHP like me not HTML. The answer was given:
$.ajax({
url: 'http://dowmian.com/xs1/getcam.php',
type: 'GET',
data: {id: <?php echo $cam_id; ?>},
success: function(responseText){
$('#update-div').html(responseText);
},
error: function(responseText){
}
});
I dont think above it answered posters question or mine as ajax is a server based push how is this relevant? as if its PHP driven the needs a refresh at server to refresh the contents not to provide new html. It is this refresh I am not interested in to re-copy PHP code elsewhere in JS as its already in my PHP. Does that make more sense?
Update
I did find a bracket missing and a set of single quotes inserted by editor. Which I have updated above but there was no significant change.
Cheers Nicolas . I am still hopeful that someone knows about Ajax as it sits underneath these technologies. I have a server side PHP file that I was hoping to use AJAX to pull just the PHP from the section it was pointing to an gUpdateDiv . As its derived from the server and created on the fly from SQL. I dont see how your answer would help push this data back in to the from the server . The $(gUpdateDiv).innerHTML was supposed to be acted upon not the whole page . What I am unsure of is how a trigger from this can update timer just this $(gUpdateDiv).innerHTML . I am also not aware if a server based refresh would do this or if the transport id provided from the file would be able to deliver just that . I think I am missing something a vital part that I dont have or have grasped yet. The reason there is two timers is effectively it checks the same file at a different point in time as its created by PHP it might be different from the first if it is i.e. the SQL data has changed, I want this to update this $(gUpdateDiv).innerHTML with the data which it compared it to the second 'Get' in the second request. It sounds, simple in practice but have got stuck comparing two versions and insuring second version gets used .
Further update placing an alert in the Javascript file did not pop up like it does here https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert however the same alert in the initiating PHP worked fine and created the alert. called the same function from the main PHP nd the alert occurred so the JavaScript is running next visit F12 on the page to see if there is any warnings or errors. Ok after adding JQuery which I thought I had added this started working however It is not doing what i Expected it to do. As the contained both text and graphics created by PHP I expected this all to be updated The graphics are not the text is any ideas? .
Further to the image problems I placed an extra line to update the image however I used this too in PHP
<script type="text/javascript">
//initpage() ;
function updateArtworkDisplay() {
document.querySelector('#np_track_artwork').src = 'images/nowplaying_artwork_2.png?' + new Date().getTime();
}
</Script>
But it didnt work to update the image in php?
<div id='outer_img'><img id='#np_track_artwork' src='/images/nowplaying_artwork_2.png' alt='Playing track artwork' width='200' height='200'></div>
in js change
/ looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
updateArtworkDisplay(); // fire up the redraw in php file.
}
}
Nearly there it does almost what it needs to apart from the redraw which is not happening
// Start Clock refresh
// uses new new Ajax.PeriodicalUpdater(
// in main fetch file to trigger the auto update of the page.
// Written by Denise Rose
var gUpdateDiv="";
var gContentURL="";
var gcheckInterval=0;
var gcheckURL = "";
var gCurrentCheck ="";
_fetchUpdater('track_data','/fetch_sql.php','/fetch_sql.php',8000);
function _fetchUpdater(updateDiv,contentURL,checkURL,checkInterval)
{
gUpdateDiv = updateDiv;
gContentURL = contentURL;
gcheckInterval = checkInterval;
gCheckURL = checkURL;
setTimeout('check();',gcheckInterval);
}
//Called by _fetchUpdater every (n) seconds determins if content should be updated.
function check()
{
new Ajax.Request(gCheckURL,{method:'get', onSuccess:'CheckResponse()'});
setTimeout('check();',gcheckInterval);
}
// looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
$time = new Date().getTime();
new Ajax.Request('outer_img', {method: 'get',onSuccess:function s() {
$('outer_img').innerHTML = "<img id='#np_track_artwork' src='/images/nowplaying_artwork_2.png?t='"+$time+" alt='Playing track artwork' width='200' height='200'>"}
});
}
}
GIVEN UP WITH THIS PLEASE DELETE MY PERSONAL INFORMATION AND POSTSript-fetch-async-await/

How to use JS to display images from database

So I made a website that displays FPS information stored in a mysql database. For each second of gameplay I have a pair of number(fps)-image(screenshot).
I display the numbers in a line chart made with JavaScript. The behaviour desired is when I click on a bullet in the chart, the screenshot for that particular second is displayed in a div on the page.
I have to mention that the screenshots are stored in the database and they are very low in size. I display then using PHP like this:
$query = "SELECT `image` FROM `logs` WHERE `session_id`=".$_GET['session']." AND `second`=".$second;
$sth = $mysqli->query($query);
$result=mysqli_fetch_array($sth);
if (!empty($result))
echo ' <img id="screen" src="data:image/jpg;base64,'.base64_encode($result['image']).'"/>';
The method I'm using now is when I click on a bullet in the chart (action recorded in JS), I send it as a GET parameter and read it with PHP afterwards, like this:
window.location.href = url + "?second=" + second;
This method obviously will refresh my page. The problem is, the chart I made also has a zoom/scroll option and that resets whenever the page is refreshed, making the experience very bad for the user.
Is there any method to display the screenshots without refreshing the page, for this particular case (where I have to query the database for each click/picture)? Maybe there is a better way of approaching this problem?
Thanks.
I think you've got 2 solutions which are Ajax or Websocket depending your needs.
AJAX
Ajax permit to asynchronously, only when you need, call the server and get datas from an URL which could be a webservice or PHP page... Perhaps, it's the better solution in your case.
To make it easy, you can use JQuery library by donwloading the script and insert it in your HTML :
<script src="jquery-3.0.0.min.js"></script>
To call the server, using JQuery :
$.ajax({
url: url + "/yourphppage.php",
data: "parameter=" + yourOptionelParameter,
async: false,
success: function(data) {
refreshYourChart(data);
},
error: function() {
alert("Your error");
},
contentType: 'charset=utf-8'
});
Or if your prefer pure javascript.
Now, you just have to work on the presentation of your data, on the server side. It could be what you want HTML, TXT, JSON, XML...
Websocket
Websocket is like a permanent tunnel opened between your server and the client. Each side can ask or send datas in real time.
It seems to be a library server side :
http://socketo.me/
And client side, it's very easy :
Nice documentation on mozilla website
Hope it helps. Good luck.
To change a picture source, as I see the easiest way is using an ajax call, so you can send any kind of parameters to your server, and in return your will get your new picture source.
$.get('urlToYourServer.com?parameter=1', function(data){
$('#img').attr('src', data.imgSrc);
})

AJAX to send a JS variable to a PHP file (and then to DB)

What I am trying to do:
I have a ready made HTML5 game incorporated onto my website - Link to game
Using this game, I want to now implement a high score board and display it on the same page.
Example, if I am logged in as Conor, Conor goes to snake_game.php where the game is located. He gets a score of three, I need the value of three, which currently is assigned to a JavaScript variable, to become a PHP variable so that I can store it into a table called high_scores in my database.
Then, once the data is in my database, I can start showing the results on the high score variable and update the data when needed.
Problem(s):
I understand that I have to use AJAX to achieve this, but I have never used AJAX before.
Resources:
snake_game.php is where the container is located where the game is displayed, as well as the high scores div:
<div id="wrapper">
<div class="game_canvas">
<canvas id="canvas" width="450" height="450"></canvas>
<script src="javascript/snake.js"></script>
</div>
<div class="high_scores" >
High scores:
</div>
</div>
snake.js is where all the JavaScript is found to create the game. All the JavaScript is available to view in the link above.
What I have tried:
From the game's JS, I believe the score is kept in a var called score - var score; - Knowing this, I have tried the below approach in an attempt to get . I have tried to watch a few tutorials online and have come up with this (located in snake_game.php):
<script type="text/javascript">
function updateScore ()
{
var score = $('score').val();
$.post('snake_game.php', {postscore: score},
function ()
{
$('high_scores').html(data);
});
}
</script>
and then PHP code:
<?php
$new_highscore= $_POST['score'];
echo json_encode($new_highscore);
?>
I believe the following get's data from the JS? But I am not sure, nor do I think it is the correct way to approach this.
Any/all help would be appreciated :)
If I were you I would not do this in vanilla php but of course you can.
Things to note:
1) You're not passing your response data into your call back method in your jQuery post
2) you aren't selecting anything with jquery
$.post('snake_game.php', {postscore: score},
function (data) // <-- pass data in here;
{
$('high_scores').html(data); //<!-- you aren't selecting anything here.
//if I were you I would make data a json
//I would have something like
$('.high_scores').append(data.high_score);
//actually I have no idea why you even have this callback here
});
3) I don't really understand you're explanation of snake_game.php. It seems like you are trying to use it as both a template and an endpoint. If you are doing things in vanilla php, which I strongly discourage you from doing, you need another php file to handle your post request. e.g. snake_high_scores.php.
//in snake_high_scores.php
//this is a really bad way to learn ajax requests. You should use a framework
$new_highscore= $_POST['score'];
//store this score in a db maybe you can pickup the user id from a session cookie
echo json_encode({data => {high_score => $some_highscore}});
In addition to above answers I would suggest whenever game loads make the high score available in page (place in a hidden element/input field if you don't want to show to user) then once the game ends then compare the user score with high score if it is greater than current one then make the Ajax call to php to store in DB.
This works for both per user (make user high score available once user logs in) or global single high score.
You can't access 'score' outside the "ready" function. If you want to implement things the way you were thinking above, you'll have to add a global reference to score, though I'll warn you that's generally frowned upon.
// Make a global reference to score
var score;
$(document).ready(function(){
//Canvas stuff
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
//Lets save the cell width in a variable for easy control
var cw = 10;
var d;
var food;
//var score; THIS NOT NEEDED ANYMORE.
You're better off adding your function with the Ajax call within the ready() function just like the code from the tutorial. The way the game works is everytime you run into a wall, the game resets itself by calling the "init" function. To do what you're wanting, before the score gets reset to zero, you want to send it to the server. See below for an idea:
function init()
{
d = "right"; //default direction
create_snake();
create_food(); //Now we can see the food particle
// Before resetting the score below, send the user score
// to the server
sendScoreToServer(score);
//finally lets display the score
score = 0;
........
EDIT:
Freddy, here's the simplest Ajax demo I can give you. You need to study this and fiddle with it until you understand what's going on. After you understand this demo below, you should be able to figure out how to do what you want above. YOU WILL NEED TO EDIT THE <SCRIPT> FILE PATHS AND AJAX URL TO AJAXDEMO.PHP IN MY EXAMPLE FILES TO MATCH YOUR SYSTEM.
In some HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Ajax Demo</title>
</head>
<body>
<input type="text" name="score" id="scoreBox"><button id="sendScore">Send Score to Server Running PHP</button>
<div id="result">The result from the server will be placed here...</div>
<script src="/resources/js/jquery-1.12.3.js"></script>
<script src="/resources/js/ajaxDemo.js"></script>
</body>
</html>
ajaxDemo.js file:
// This function uses AJAX to send the score from the HTML page running javascript to a web server running PHP.
function sendScoreToServer(theScore) {
$.ajax({
type: "POST",
url: "http://localhost/ajaxDemo.php",
data: { score: theScore },
dataType: 'json',
success: function(response){
console.log(response);
$('#result').html('The score returned by the server is: '+response.scoreDoubled);
}
});
}
// Once the HTML page finishes loading, this binds a 'onClick' event to the button that causes it to trigger the sendScoreToServer function.
$( document ).ready(function() {
$('#sendScore').on('click', function() {
var score = $('#scoreBox').val();
sendScoreToServer(score);
});
});
In ajaxDemo.php file on the server:
<?php
$result = [];
$result['scoreDoubled'] = $_POST['score'] * 2;
echo json_encode($result);
Final Encouragement:
It sounds to me like you might be slightly confused regarding front-end code vs. back-end code and what the difference is. Just remember that Front-End code runs on the USER'S computer. So when you visit that game tutorial website and it loads the Snake game... that game is running on YOUR computer. Back-End code (PHP is a back-end language) is code that runs on a web server... meaning generally NOT on your computer. By running a web server on your machine with "localhost", you are essentially having your PC 'pretend' to be a web site so you can quickly test and develop your application. Thus any Ajax calls to 'localhost' never have to leave your machine. HOWEVER, in a normal usage environment, an Ajax call would be sending a request over the internet to some remote server such as www.MySite.com. MySite.com would then process the info sent to it using PHP or some other language, then send a response back, which gets processed by the "success" function attached to the ajax request. The "success" function (commonly called a 'callback' function) then updates the HTML page with some result based on what the server sent back.

Constantly read JSON database

I want to constantly read a JSON-formatted js file so my page shows the changes of that file.
I want some content in my page to change everytime I change the database file within the directory.
My files are:
objectoJSON.js:
var rightFencer;
rightFencer = {"name":"Jorge ANZOLA","nacionality":"VEN","points":10};
var leftFencer;
leftFencer = {"name":"John DOE","nacionality":"USA","points":5};
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<center><p id="rightFencerName"></p><p id="rightFencerPoints"></p> - <p id="leftFencerName"></p> <p id="leftFencerPoints"></p></center>
<script src="objetoJSON.js"></script>
<script>
document.getElementById("rightFencerName").innerHTML = rightFencer.name;
document.getElementById("leftFencerName").innerHTML = leftFencer.name;
document.getElementById("rightFencerPoints").innerHTML = rightFencer.points;
document.getElementById("leftFencerPoints").innerHTML = leftFencer.points;
</script>
</body>
</html>
I thought about putting those two scripts into an infinite while loop so by the time I change the file in the directory, it'd change. But it didn't work.
Also, I thought about using setInterval() to run the scripts every few seconds, but I didn't know how to make it work.
As you can see, I'm a complete noob, so ANY idea would be very appreciated.
Your "objectoJSON.js" is not a JSON file... it's a simple javascript object.
A JSON file would be something like this.
{
"rightFencer":{
"name":"Jorge ANZOLA",
"nacionality":"VEN",
"points":10
},
"leftFencer":{
"name":"John DOE",
"nacionality":"USA",
"points":5
}
}
What you are searching for is
Ajax, Server Sent Events or webSockets
Those update the pagecontent without the need to refresh the page or clicking something.
The following codes shows how to interact with each technology.
They have many advantages and disadvantages... to many to write right now.
ask specific and i can add that to the answer.
All the following examples are pure javascript and so don't need any type of library.They work with almost all new browsers... ios,android,windows also.
All the following examples could be adapted to work with a non properly formatted json file like that you posted. Look at the bottom.
Ajax:
Client asks for data
This updates the client every 30seconds.
function $(a){
return document.getElementById(a)
}
function ajax(a,b,c){ // Url, Callback, just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function reloadData(){
ajax('database.js',updateText)
};
function updateText(){
var db=JSON.parse(this.response);
$("rightFencerName").innerHTML=db.rightFencer.name;
$("leftFencerName").innerHTML=db.leftFencer.name;
$("rightFencerPoints").innerHTML=db.rightFencer.points;
$("leftFencerPoints").innerHTML=db.leftFencer.points;
}
window.setInterval(reloadData,30000);//30 seconds
/*setinterval is a very bad way to update stuff ,
especially with ajax.. there are many other ways to do that.*/
Ajax does not need any type of server if you read the JS file locally.
Also appendding it... but both examples are time based... and that is not good if you have many users online. WS & SSE allow you to update each user individually depending on the necessity.
SSE:
Server sends data when needed
This uses php to create a Server Sent Events Server
Also this updates the client every 30 seconds, but in this case the server updates the client. Using Ajax the client asks the server to update.
The php file "sse.php"
header('Content-Type: text/event-stream'); // specific sse mimetype
header('Cache-Control: no-cache'); // no cache
while(true) {
if(/*something changes*/){
echo "id: ".time().PHP_EOL;
echo "data: ".$data.PHP_EOL;
echo PHP_EOL;
}
ob_flush(); // clear memory
flush(); // clear memory
sleep(30);// seconds
}
The javascript file
function $(a){
return document.getElementById(a)
}
function updateText(e){
var db=JSON.parse(e.data);
$("rightFencerName").innerHTML=db.rightFencer.name;
$("leftFencerName").innerHTML=db.leftFencer.name;
$("rightFencerPoints").innerHTML=db.rightFencer.points;
$("leftFencerPoints").innerHTML=db.leftFencer.points;
}
var sse=new EventSource("sse.php");
sse.onmessage=updateText;
WebSockets:
Server sends data when needed, Client asks for data when needed
webSockets is cool ... comunication is bidirectional. it is fast. but you need something like a nodejs server to be able to handle it properly.
function $(a){
return document.getElementById(a)
}
function updateText(e){
var db=JSON.parse(e.data);
$("rightFencerName").innerHTML=db.rightFencer.name;
$("leftFencerName").innerHTML=db.leftFencer.name;
$("rightFencerPoints").innerHTML=db.rightFencer.points;
$("leftFencerPoints").innerHTML=db.leftFencer.points;
}
var ws=new WebSocket('ws://YOURIP:YOURPORT');
/*ws.onopen=function(){ //those events are also aviable with sse
ws.send('WS open!');//sending data to the server
};
ws.onclose=function(){
console.log('WS closed!');
};*/
ws.onmessage=updateText;
Adapting the js
Ajax..
load the "objectoJSON.js" with ajax and evulate it ... but not using eval(). eval is evil. use new Function()
function updateText(){
document.getElementById("rightFencerName").innerHTML = rightFencer.name;
document.getElementById("leftFencerName").innerHTML = leftFencer.name;
document.getElementById("rightFencerPoints").innerHTML = rightFencer.points;
document.getElementById("leftFencerPoints").innerHTML = leftFencer.points;
}
(new Function(this.response+'\n updateText()'))();
or append the script every 30 seconds or whatever....
I don't write that example as it is the worst approach.
With 30 clients it means that you have to read the file from server evey second.
With SSE or WS you read it once and broadcast it to hundreds of clients.
I suggest to fix your json file.
if you have any other questions ask.
I guess you are working with framework which supports websockets.
You could listen for a change in file using websocket.it may return change in data set like new record or update on any record, or using javascript/ajax call get latest content from server and update your HTML.
https://www.websocket.org/demos.html, see foreign exchange dashboard to see how websockets can be used for constantly updating data.
The way you are doing it now isn't scalable, testable or manageable.
You really don't want to save data on the server using plaintext json files.
If you want a more robust framework for handling your use case, I suggest using web sockets on both the client side and server side (socket.io is a great choice), and using RethinkDB on your server as the DB.

Real time insertion of data in mvc

I have a news project with comment feature. Any one who add a comment can see his comment immediately without reloading the page ( using ajax ). The problem is that when user1 ( for example ) comment on post1 , only user1 can see his comment immediately but all other users need to reload the page to see the comment of user1. How can I solve this problem ?
The code I am using to get the comment :
$(function () {
$("#AddComment").click(function () {
var CommentText = document.getElementById("CommetForm").innerHTML;
var UserName = document.getElementById("UserName").innerHTML;
var PostId = document.getElementById("PostId").innerHTML;
$.ajax({
url: '/PostComment/AddComment',
type: 'POST',
dataType: 'json',
cache: false,
data: { "PostId": PostId, "CommentText": OrignalCommentText },
success: function (data)
{
if (data == "P") // Commet Stored on database successfully
{
document.getElementById("PostComments-" + PostId).innerHTML +=
"<li>" +
"<div class='media'>" +
"<div class='media-body'>" +
"<a href='' class='comment-author'>"+UserName+"</a>" +
"<span class='CommetText' id='CommentText-" + PostId + "'>" + CommentText + "</span>" +
"</div>" +
"</div>" +
"</li>";
}
else // Some Error occur during storing database
{
document.getElementById("CommentError-" + PostId).innerHTML = "\nSomething went wrog, please try agin";
}
}
});
});
});
And This code for storing comment in database :
private SocialMediaDatabaseContext db = new SocialMediaDatabaseContext();
[HttpPost]
public JsonResult AddComment(string PostId, string CommentText)
{
try
{
Users CurrentUser = (Users)Session["CurrentUser"];
PostComment postcomment = new PostComment();
CommentText = System.Uri.UnescapeDataString(CommentText);
postcomment.PostId = int.Parse(PostId);
postcomment.CommentFromId = CurrentUser.UserId;
postcomment.CommentText = CommentText;
postcomment.CommentDate = DateTime.Now;
db.PostComments.Add(postcomment);
db.SaveChanges();
return Json("P");
}
catch
{
return Json("F");
}
}
I suggest you use SignalR for this. http://www.asp.net/signalr/overview/getting-started/introduction-to-signalr
TL;DR Use can use setInterval or Websockets to accomplish this. Below I explain how.
First of all, we need to understand what is behind this Publish/Subscribe pattern. Since you want to build a real-time application, you may create a function that asks to your server if some data was added since last time it was checked.
USING WindowTimers.setInterval()
Here is the simplest way to accomplish this in my point of view, assuming that's your first time and you never worked with websockets before. For instance, in your client-side project you create a function within a setInterval setInterval( checkNewData, time). Your method checkNewData() will make an ajax requisition to your server, asking if some data was added recently:
function checkNewData() {
// ajax call
// On response, if found some new comment, you will inject it in the DOM
}
Then, in your server-side method, get the timestamp of its call and verify in your database if there are some data. Something like this:
// Method written in PHP
public function ajax_checkNewData() {
$time = time();
// Asks to your model controller if has something new for us.
// SELECT comment FROM comments WHERE timestamp > $time
// Then return its response
}
You will use the response that came from your controller method ajax_checkNewData() to write on your comments-container.
USING WEBSOCKETS (beautiful way)
Now, there are another way to do this, using WebSockets. HTML5 WebSocket represents the first major upgrade in the history of web communications. Before WebSocket, all communication between web clients and servers relied only on HTTP. Now, dynamic data can flow freely over WebSocket connections that are persistent (always on), full duplex (simultaneously bi-directional) and blazingly fast. Amongst different libraries and frameworks, you can use socket.io. I believe this will solve your real-time application problem pretty good, but I am not sure how much of your project you will need to change to suit this solution.
Check it out the simple chat tutorial from SocketIo page and see for yourself if it fits to your needs. Its pretty neat and would be a good challenge to implement using it. Since its event-driven, I believe you wont have problems implementing it.
For further information check it out:
REFERENCES
Get Started: Chat application - http://socket.io/get-started/chat/
Websockets - http://en.wikipedia.org/wiki/WebSocket
WebSockets - https://developer.mozilla.org/en/docs/WebSockets
Good luck!
You could write a JavaScript code which makes ajax call to a servlet that checks for updates in the database.
Return a flag to the success function of the ajax call and If the state has changed or any comment added to the database, you can reload the page or refresh the consisting of the comments with the new comments.
It's not posting on other pages, because the user1 page is making an AJAX call, so it loads correctly. However, the other pages don't 'know' they are supposed to reload via AJAX. You need some kind of timed loop running that checks for any changes. Either of the above answers should work for it.
You could use SignalR for this, you can send realtime messages to the server, here is a sample to know how to implement SignalR in ASP.NET MVC
https://github.com/WaleedChayeb/SignalRChatApp

Categories

Resources