How to use Comet and Push technique using AJAX and PHP - javascript

I am calling an AJAX after each 5 seconds to update the some info of current logged-in user into database table in PHP.
But it creates a heavy load on my website, and website down after some time when there are multiple users logged-in on my website.
Is there any way to use some other techniques like Comet or Push to improve my script?
Here is a code i am using:
Javascript code:
jQuery(document).ready(function ($) {
update_data();
function update_data() {
$.ajax({
type: "POST",
url: "$URL",
data: {update_current_time:1},
success: function(response){
setTimeout(update_data, 5000);
},
error: function(){
setTimeout(update_data, 5000);
}
});
}
});
PHP code:
if(isset($_POST['update_current_time']))
{
$query = "UPDATE users SET user_timer=now() WHERE user_id=".$_SESSION['id'];
$db->execute();
echo 'success';
die;
}

To use push or comet you will need to setup up a "webserver" that will listen to some port. So this cannot be solved using pure php but needs a listener setup (unless you create your on listening server using php).
To stay at php you can check out ratchet.
Another common way to go would be a node.js server parrallel to your webserver.

If I ever encounter this use case, My Implementation would be using the session variable. Instead of writing to database every 5 seconds, I'd store the request timestamps in $_SESSION for like 1-2 Minutes, and then write the whole data at once. For this example lets consider that you wish to make it a minute(60 sec).
So the algorithm would be
Make the request from client side.
On the server check if the session variable $_SESSION['requestcount'] is set.
If its not set, then I shall set that variable to 1, also I'll store the timestamp in some sub-array and return status 200 OK.
If its set I'll check if the value for $_SESSION['requestcount'] is 12 (1 request every 5 seconds x 12).
If the value of $_SESSION['requestcount'] is less than 12 then I'll increment its value by 1 and return status 200 OK.
If the value of $_SESSION['requestcount'] is equal to or grater than 12 then I'll Get all data from the sub-array and prepare it to insert inside the database, Also reset the $_SESSION['requestcount'] to 0, if all is well return status 200 OK.

Related

Add Variable to PHP Session Array From Dynamically created HTML element within PHP Echo [duplicate]

Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

Real Time Refresh / Update

I have a MVC 3 project that publish in a server.
Scenario
For example I have a function for saving a data from (PC1) to (PC2).
It is possible that the viewing of data(data in jqgrid) in (PC2) is open(open in page) by a user and it will auto refresh or update the page or the jqgrid after the (PC1) save a data?
My jqgrid version is 4.3.3.
Hope you guys understand what I mean in my post. Post feedback if down votes. Thanks.
Any help will be accepted.
You might wonna use ajax to accomplish such a job, please read below
if I understand what you mean, is that you wonna poll a server to realtime updates on either intervals or something else...
option 1
Issue a normal stateless ajax call to the server, then force the server to hold the request for a limited time [to overcome server overhead]
This can also be reffered to as reverse ajax or comet.
Unless you are planning to use websocket technology, I hardly stress that you try this.
if(isset($_GET['finite'])){
#declare time for a session
$_SESSION['typing']=$reduce_browser_overhead=time();
#remember to close the session before entering the loop;
#if u dont close, then the browser will not reload the same website untill the connection is close or satisfied
session_write_close();
function loop(){
#do this to access external variables ===> $reduce_browser_overhead;
global $con,$reduce_browser_overhead;
#explicitly check 2exit
#please do this to release mysql connection since they are in a loop
if($reduce_browser_overhead+4<time()){
echo ' ';ob_flush();flush();
if(connection_aborted()){
#do some work here before you finally exit the connection
exit;
}$reduce_browser_overhead=time();
}
#php prepare statement...
$looper=$con->prepare("SELECT ROW FROM TABLE WHERE ID=SOMETHING AND $_SESSION[typing]=SOME_ROW");
#The statement above willcause the loop to work
#If a table had been update and table has not yet updated, this sql will detemin by the current time
#meaning that if the time[integer] of SOME_ROW is not equal to the time in the session variable,
#then it will let go to the client and then again it will continue looping untill the time in the
#SOME TABLE ROW changes....
$looper->execute();
$looper->store_result();
if($looper->num_rows>0){
sleep(2);
#do some work before looping again
loop();
#you have to explicitly return to this loop to work as expected.
return;
}else{
#send back data to the user or the client listening on the connection
session_start();$_SESSION['typing']=time();session_write_close();
#update the session before finishing the request so that the next time the request comes, the time will be equal to the DBserver time in the row and hence causing the loop again and again => more like a cycle
echo 'After some time the server has received new data which is =>> '.$newdata;
}
}loop();
exit;
//In another file on in the same document as the php / your server file ==> do javascript below
//first issue a normal / stateless ajax request to the target server
$.ajax({
//All optional but url required!
url:'abc.php?var_one=blabla',
cache:true,//whether to cache the requests
timeout:(1000*60)*20,//timeoutthe request
success:function(data){
//if the server successfully completed the request
//do some work here with data returned
},
error:function(){
//if the server return an error
//do more work around
//or call the function again
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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);
})

Edit Session Through PHP Script

At page 0 inputs are entered. Then Page 0 is submitted to php page 1
At php page 1 i calculate $Ama;
At php page 2 (required by page1), i need to ask one more verification check.
Hence in php page 2 :
if($Ama ==0 )
{
echo '<script>
var a = confirm("Ama is Zero. Are you sure?";
if(a){
//Set A SESSION VARIABLE
}
</script>';
}
How do i append to this a $_SESSION['Accepted']=0 where marked in Code.? I am having a problem with syntax to append this.
Since this confirm() check is done on client side, you can't run PHP code, so you will have to use AJAX to send request to server to append whatever values you want to the session.
There are many tutorials available, here is a simple way to do AJAX calls using jQuery http://api.jquery.com/jquery.ajax/
You can't manipulate a session value from Javascript, they only exist on the server.

making a loop with jquery, Ajax and PHP

i want to make a loop in jquery, Ajax and PHP.
my pages are:
shop.php
do_ajax.php
in the shop.php are variable $p_productid is 1 and $j_productid is $p_productid
var j_productid = <?= $p_productid ?>;
now i do j_productid++ so the output from $j_productid is 2
now i'm posting this with ajax to do_ajax.php
in the do_ajax.php are variable $pa_productid is $_POST['$j_productid'];
now i can place this on html, but i want to set this value in too the variable on $p_productid on shop.php
how i need to do this?
there is working a swipe system in this case so only with php it isnt working i need to work with jquery that's why am i doing this on this way. i got an another solution without AJAX but i want that you cant see on the client side the webpage is refreshing.
JQUERY
wipeLeft: function() {
var j_ProductId = <?= $g_ProductId ?>;
var j_Swiped = 1;
if (j_ProductId < <?= $l_LastProduct ?>){
j_ProductId++
//document.swiping.productid.value = j_ProductId;
//document.swiping.submit();
$.ajax({
url: 'do_ajax.php',
type: 'POST',
data: { swipe : j_Swiped,
productid : j_ProductId},
success: function (data) {
$('.product').html(data);
}
});
}
}
do_ajax.php
if(!empty($_POST['swipe'])){
$l_ProductId = $_POST['productid'];
echo $l_ProductId;
}
You need to understand that the JavaScript (even if generated dynamically by PHP) is not running the same time that PHP is running. Your workflow will be something like this:
PHP script (shop.php) is invoked
PHP script generates output, HTML and JS mixed.
These are all in server side until the web server sends the output to client (browser)
In browser HTML displays and JS runs with starting values that you generated previously by PHP. But in this time, PHP has been finished, not running anymore. PHP variables are not alive anymore.
JS interacts with the user in browser, we can say it's running continuously.
Triggered by an action (swipe) JS sends an (ajax) request from client side to server side. This request transfers the new value to server side, and invokes another PHP script (do_ajax.php). You do whatever you want with the new value (process it and or store it) in server side. You need to understand that you are in a completely disjunct scope in PHP than in your first PHP script. (distinct in time too)
If you want to be sure that, in case of a page reload, the (product ID) value will be the updated value, you need to store it somewhere (user session, key-value store, database, or any persistent) when you get it in server side (so in do_ajax.php) and later load this value in the beginning of your shop.php script ...which will pass it to the JS, and so on. The workflow starts again.

Categories

Resources