Jquery still doesn't run when page created by php script [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I find the Jquery script I have refuses to run when the page has been generated by my php script.
I would appreciate a different pair of eyes to look over my code please.
<?php
.
. DB log in and verification done here
.
.
<html><head><link href="css/stylesheet.css" type="text/css" rel="stylesheet" />
<style>body { background-image: url(../riders/'.$riderno.'/rider_picture.jpg);background-repeat: no-repeat;background-attachment: fixed;top: 10%;background-position: center;}
</style><script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".dialog").dialog({
autoOpen: false,
});
$(".session").click(function () {
var src = $(this).data("href");
var title = $(this).data("id");
alert("Clicked - " + src);
var $dialog = $("<div></div>")
.html("<iframe style="border: 1px; " src="'+ src + '" width="100%" height="100%"></iframe>")
.dialog({
autoOpen: false,
modal: true,
height: 625,
width: $(window).width() - 20,
height: $(window).height() - 20,
title: title
});
$dialog.dialog("open");
});
});
</script></head>
<body><div class="RiderInfo">
<?php
echo "<div class='Week'>";
$total_duration = date("H:i:s", strtotime("0:0:0"));
$total_distance = 0;
$total_tss = 0;
$total_hrtss = 0;
$avg_if = 0;
$avg_hrif = 0;
$sessions = 0;
$sql = "SELECT * FROM `RiderLog` WHERE `RiderNo` = $riderno AND `RideDate` >= '$startdate' AND `RideDate` < '$enddate' ORDER by RideDate ASC";
$result = $mysqli->query($sql) or die($mysqli->error.__LINE__);
$record=0;
if($result->num_rows > 0) {
$thisdate = $startdate;
$row = $result->fetch_assoc();
do {
echo "<div class='date'><div class='day'><strong>".date("D", strtotime($thisdate))."</strong></div>";
while ($thisdate == date("Y-m-d", strtotime($row['RideDate']))) {
$sessions++;
?><button data-id='#dialog<?php echo $record?>' class='session' data-href='fitanalysis.php?rider=<?php echo $riderno ?>&file=<?php echo $row['FIT_file']?>'><div class='duration'><?php echo $row['Duration']?></div><div class='distance'><?php echo $row['Distance'] ?>km</div>
<?php $total_duration = date("H:i:s",strtotime($total_duration)+(strtotime($row['Duration'])-strtotime("00:00:00")));
$total_distance += $row['Distance'];
?></button><?php
$row = $result->fetch_assoc();
$record++;
}
$thisdate = date("Y-m-d",strtotime($thisdate.'+ 1 day'));
echo "</div>";
} while ($thisdate <= $enddate);
echo "<div class='WeekSummary'><strong>Week Summary</strong><br>Duration : ".date("H:i:s", strtotime($total_duration))."<br>Distance : $total_distance km<br>TSS : $total_tss<br>Average IF : ".$avg_if/$sessions."</div>";
echo "</form>";
} else {
clear up and finish html page.

Well a few thing first of all, this probably isn't going to work out well for you. You should replace that leading double quote with a single one.
.html("<iframe style="border: 1px; " src="'+
Secondly, this really just irritates me
var $dialog = $("<div></div>")
is this javascript or PHP? Using the $ for javascript variables is unnecessary and just makes the code harder to read.
Whats all this at the top a
<?php
.
. DB log in and verification done here
.
.
<html><head><link href="css/stylesheet.css" type="text/css" rel="stylesheet" />
<style>body { background-image: url(../riders/'.$riderno.'/rider_picture.jpg);background-repeat: no-repeat;background-attachment: fixed;top: 10%;background-position: center;}
</style><script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
Then latter you have
<?php
but never close the first one? Kind of a mess going on there.

Related

Google Charts show just one entry of MySQL when connected?

I have the following Google Charts code and I'm trying to connect it with MySQL, I have tried each and everything with it available on the internet but it still shows just one entry of SQL result set, although I have 10 entries in it. On the internet I found the $row_num counter thing and since including it in my code, I have been able to query one entry but I want to query all entries with it. Please help me with this and let me know what mistake (if any) I have been making, Following is my PHP code:
[<?php
``$dbhandle= new mysqli('localhost','root','8317','record');
//echo $dbhandle->connect_error();
$query= "SELECT * from download_manager";
$res= $dbhandle->query($query);
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':\['bar'\]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable(\[
\['Title', 'No. of Downloads'\],
<?php
$total_rows = mysqli_num_rows($res);
$row_num = 0;
if (mysqli_num_rows($res) > 0) {
while($row=$res->fetch_assoc())
{
$row_num++;
if ($row_num == $total_rows){
echo "\['".$row\['filename'\]."',".$row\['downloads'\]."\]";
}
}
}
else
{
echo "0 results";
}
?>
\]);
var options = {
width: 800,
chart: {
'title': 'Top 10 Downloads',
subtitle: 'for the last month'
},
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
}
};
var chart = new google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
};
</script>
</head>
<body>
See Also : Downloads in the Last 7 Years <br> <br>
<div id="dual_x_div" style="width: 900px; height: 500px;"></div>
</body>
</html>][1]
You have missed adding a comma , in your PHP data loop. Try with the following:
echo "\['".$row\['filename'\]."',".$row\['downloads'\]."\],";

jQuery post from php variable

I'm in the process of creating a 'drag-and-drop' ordering list, and I grabbed some code for an existing one and I need to modify it to fit my needs. However I do not fully understand exactly what the code is doing in order to modify it correctly.
Basically I have a php variable '$draft_id' that I need to pass into my updateList.php. If I just define $draft_id=0 within updateList.php it works fine, but I need to be able to pass this value in.
The code looks like:
(index.php)
<script type="text/javascript">
$(document).ready(function(){
function slideout(){
setTimeout(function(){
$("#response").slideUp("slow", function () {});
}, 2000);}
$("#response").hide();
$(function() {
$("#list ul").sortable({ opacity: 0.8, cursor: 'move', update:function() {
var order = $(this).sortable("serialize") + '&update=update';
$.post("updateList.php", order, function(theResponse){
$("#response").html(theResponse);
$("#response").slideDown('slow');
slideout();
});
}
});
});
});
</script>
...
<?php
include("connect.php");
$draft_id='0';
$query = "SELECT id, text FROM sort WHERE draft_id =" . $draft_id . " ORDER BY listorder ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$id = stripslashes($row['id']);
$text = stripslashes($row['text']);
echo "<li id='arrayorder_" . $id . "'>" . $text;
echo "<div class='clear'></div>";
echo "</li>";
}
?>
(updateList.php)
<?php
include("connect.php");
$array = $_POST['arrayorder'];
if ($_POST['update'] == "update"){
$count = 1;
//------------------------------------
$draft_id=$_POST['draft_id'];
//------------------------------------
foreach ($array as $idval) {
$query = "UPDATE sort SET listorder = " . $count . " WHERE id = " . $idval . " AND draft_id=" . $draft_id;
mysql_query($query) or die('Error, insert query failed');
$count ++;
}
echo 'Draft Order Saved!';
}
?>
So basically in the 'updateList.php' I'd like 'draft_id' to be taken from the $_POST array, but I'm not sure how to pass it correctly. Any help would be appreciated.
After some research I've figured out how pass this how it needs to be passed, so I figured I'd share in case anyone else needs it in the future. So my main issue was that I did not understand exactly how the $_POST array was being set.
In the Javascript there is a $.post that is using a variable 'order' which is defined above it. This is where the $_POST array is being passed. So by adding an additional condition you can pass additional variables in the $_POST array.
So I changed:
<script type="text/javascript">
$(document).ready(function(){
function slideout(){
setTimeout(function(){
$("#response").slideUp("slow", function () {});
}, 2000);}
$("#response").hide();
$(function() {
$("#list ul").sortable({ opacity: 0.8, cursor: 'move', update:function() {
var order = $(this).sortable("serialize") + '&update=update';
$.post("updateList.php", order, function(theResponse){
$("#response").html(theResponse);
$("#response").slideDown('slow');
slideout();
});
}
});
});
});
</script>
to:
<?php //this will later be pulled from another page, but for now
$draft_id='0'; //I just set it up for testing purposes.
$_POST['draft_id']=$draft_id;
?>
<script type="text/javascript">
$(document).ready(function(){
function slideout(){
setTimeout(function(){
$("#response").slideUp("slow", function () {});
}, 2000);}
$("#response").hide();
$(function() {
$("#list ul").sortable({ opacity: 0.8, cursor: 'move', update:function() {
//we will add &draft_id='the php variable $draft_id to the order variable'
var order = $(this).sortable("serialize") + '&update=update' + '&draft_id=<?php echo $draft_id; ?>';
$.post("updateList.php", order, function(theResponse){
$("#response").html(theResponse);
$("#response").slideDown('slow');
slideout();
});
}
});
});
});
</script>
This fixed my issue, hopefully this can help someone out in the future if they run into this same issue.

Data still not displaying using jqGrid after doing some tips found around the net

I'm still having difficulty displaying data using jqGrid. I found some resources that might help me like the one found here and even copying the code found here.
I've been trying to solve this for so many hours but still I fail to do so. Can someone please help me? The following are the codes I currently have:
HTML/Javascript code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" media="screen" href="css/smoothness/jquery-ui- 1.10.3.custom.min.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css"/>
<style>
html, body {
margin: 0;
padding: 0;
font-size: 75%;
}
</style>
<script type="text/javascript" src="js/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript" src="js/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="js/jquery.jqGrid.min.js"></script>
<script type="text/javascript">
jQuery().ready(function (){
jQuery("#adminlist").jqGrid({
url:'cnc_admin_search.php',
datatype: "json",
colNames:['Record ID','Admin ID', 'Password', 'Last Name','First Name','Type Code'],
colModel:[
{name:'id',index:'id', width:55},
{name:'adminid',index:'adminid', width:90, jsonmap:"adminid"},
{name:'adminpass',index:'adminpass asc, adminid', width:100},
{name:'lname',index:'lname', width:80, align:"right"},
{name:'fname',index:'fname', width:80, align:"right"},
{name:'admintype',index:'admintype', width:80,align:"right"}
],
rowNum:10,
rowList:[10,20,30],
pager: '#adminpager',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
jsonReader: {
repeatitems: false,
id: "id",
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
caption: "JSON Mapping",
height: '100%'
}).navGrid('#adminpager',{edit:false,add:false,del:false});
});
</script>
<title>Administrator Panel - Super Administrator</title>
</head>
<body>
<header>
<h2>Administrator Panel - Super Administrator</h2>
</header>
<div class="content">
<table id="adminlist"><tr><td></td></tr></table>
<div id="adminpager"></div>
</div>
<footer></footer>
</body>
</html>
PHP/Database Code:
<?php
$page = 1; // get the requested page
$limit = 10; // get how many rows we want to have into the grid
$sidx = 0; // get index row - i.e. user click to sort
$sord = 'desc'; // get the direction
if(!$sidx) $sidx =1;
// connect to the database
$db = mysql_connect('localhost', 'root', '')
or die("Connection Error: " . mysql_error());
mysql_select_db('caneco_db') or die("Error conecting to db.");
$result = mysql_query("SELECT COUNT(*) AS count FROM caneco_admintable");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * FROM caneco_admintable ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysql_query( $SQL ) or die("Couldnt execute query.".mysql_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$responce->rows[$i]=$row;
$i++;
}
json_encode($responce); // coment if php 5
break;
?>
I hope someone will be able to help me. Thank you.
UPDATE:
I included the json data encoded by my php file:
{"page":1,"total":1,"records":"2","rows":[{"Admin_UserNum":"751497003","Admin_UserID":"jrmthibaler","Admin_Passwrd":"44c8ac3a1f03f006febc1075b2ba567d","Admin_LastName":"Hibaler","Admin_FirstName":"Jairo","Admin_TypeCode":"1"}, {"Admin_UserNum":"704006278","Admin_UserID":"rojaihibaler","Admin_Passwrd":"8810534d4f44d557d92a2110d664dcf6","Admin_LastName":"Hibaler","Admin_FirstName":"Jairo","Admin_TypeCode":"2"}]}
This was the JSON data produced by the php file I included previously. However there's an error saying 'Creating an object from empty value in Line 25' namely the following line of code:
$responce->page = $page;
What could possibly be wrong with that line of code? The other two similar lines of code didn't generate the same error.

php/html with flot and mysql

I have issues with my javascript. Currently, I'm working on this javascript using flot to generate a graph, first by extracting data from mysql via php and then using json_encode to output the array data which will be used in the javascript. I'm not able to spot my mistake as to why my graph isn't plotting. Thanks!
<?php
include ('config2.php');
$tbl_name4 = EITMBS;
$data = array();
$sql="SELECT * FROM $tbl_name4";
$result=mysqli_query($link, $sql);
$row_cnt = mysqli_num_rows($result);
for ($nrow = 1; $nrow <= $row_cnt; $nrow=$nrow+1)
{
$sql="SELECT * FROM $tbl_name4 WHERE id = '$nrow'";
$result=mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$data[$nrow] = $row[Power];
echo $data[1];
echo $data[2];
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Power Consumption</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>
</head>
<body>
<h1>Power Consumption</h1>
<div id="placeholder" style="width:600px;height:300px"></div>
<p id="hoverdata">Mouse hovers at
(<span id="x">0</span>, <span id="y">0</span>). <span id="clickdata"></span></p>
<p>A tooltip is easy to build with a bit of jQuery code and the
data returned from the plot.</p>
<p><input id="enableTooltip" type="checkbox">Enable tooltip</p>
<script type="text/javascript">
$(function () {
var graph = [];
var power = <?php echo json_encode($data);?>;
for (var i = 1; i < 9; i += 1) {
//alert(power[i]);
graph([i,[power(i)]);
}
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "cos(x)" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 }
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
border: '1px solid #fdd',
padding: '2px',
'background-color': '#fee',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#placeholder").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if ($("#enableTooltip:checked").length > 0) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY,
item.series.label + " of " + x + " = " + y);
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
}
});
$("#placeholder").bind("plotclick", function (event, pos, item) {
if (item) {
$("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
plot.highlight(item.series, item.datapoint);
}
});
});
</script>
</body>
</html>
Your variable var power contains an object of integers for keys and floating point numbers in string format. You may have the wrong datatype enforced in your database (for mysql looks like you should be using FLOAT).
If you have PHP 5.3.3+ you can use the following to ensure numbers are stored in number format in a json encoded string:
json_encode($data, JSON_NUMERIC_CHECK);
If not you can cycle through the array before you json encode it:
for ($i in $data) {
$data[$i] = (float) $data[$i];
}
Secondly you are incorrectly converting the json encoded object to an array. Change:
graph([i,[power(i)]);
to:
graph.push([i, power[i]]);

long polling with PHP and AJAX... almost there

I am working with a school project. The basic ide of the project is, that we have some arduino boxes the sends some sensor data to a mysql db and we have a website that display it. Sensor data is sending lets say every 6sec.
I donĀ“t have a lot of experience with PHP. But i am tinkerin my way, learing step by step..cowboy style? =)
The html/ajax/css:
<!DOCTYPE html>
<html>
<head>
<title>Arduino event poller</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type = "text/css" media="screen">
body{ font:13px/1.5 "helvetica neue", helvetica, arial, san-serif; background:#FFF; }
#main{ width:430px; height: 300px; display:block; padding:10px 0; float: left; overflow: auto;}
.event { display:block; background: #ececec; width:380px; padding:10px; margin:10px; overflow:hidden; text-align: left; }
.event img { display:block; float:left; margin-right:10px; }
.event p { font-weight: bold; }
.event img + p { display:inline; }
.patient-name { display:inline; color: #999999; font-size: 9px; line-height:inherit; padding-left: 5px; }
.event-text{ color: #999999; font-size: 12px; padding-left: 5px; }
.event-timestamp{ color: #000; padding-left: 5px; font-size: 9px;}
</style>
<script type="text/javascript" charset="utf-8">
var timeStamp = null;
/* Simple helper to add some divs.*/
function addevents(patientroom, patientname, eventtyp, timestamp)
{
$("#main").append(
"<div class='event'>"
"<p>" + patientroom + "</p>"
"<p class='patient-name'>" + patientname + "</p>"
"<p class='event-text'>" + eventtyp + "</p>"
"<p class='event-timestamp'>" + timestamp + "</p>"
"</div>"
);
}
/*This requests the url "getevents.php" When it complete*/
function waitForEvents()
{
$.ajax({
type: "GET",
url: "getevents.php?timeStamp=" + timeStamp,
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data, textStatus, jqXHR) /* called when request to getevents.php completes */
{
addevents(data.patientroom, data.patientname, data.eventtyp, data.timestamp);
setTimeout(
waitForEvents, /* Request next event */
1000 /* ..after 1 seconds */
);
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("Error:" + textStatus + " (" + errorThrown + ")");
setTimeout(
'waitForEvents()', /* Try again after.. */
"5000"); /* milliseconds (5seconds) */
},
});
};
$(document).ready(function(){
waitForEvents(); /* Start the inital request */
});
</script>
</head>
<body>
<div id="main">
</div>
</body>
</html>
My backend php:
<?php
function getEvents()
{
$con = mysql_connect("localhost","***","***");
if(!con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("arduino_db",$con);
$result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1");
if($result)
{
$patientroom = $row['rumNr'];
$patientname = $row['inneboendeNamn'];
$eventtyp = $row['handelse'];
$timestamp = $row['timestamp'];
}
if($row)
{
header('application/json');
echo json_encode($row);
exit;
}
$lastmodif = isset($_GET['timeStamp']) ? $_GET['timeStamp'] : 0;
$currentmodif = filemtime($result);
while($currentmodif <= $lastmodif)
{
unsleepp(1000);
clearstatcache();
$currentmodif = filemtime($result);
}
}
?>
My question:
How to I fetch each row from the db and return each row in JSON format to the method "waitForEvents" in the frontend.
The example doesn't have to be scaleable, secure or complete, it just needs to work =)
UPDATE: new code based on Johns tips. All I gets is a blank page, and no errors.
The first thing that popped out to me is that your MySQL call is sort of blown.
When you run this line:
$result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1");
You're going to get a MySQL resource. You need to utilize that to get your row:
$result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1");
if ($result)
{
$row = mysql_fetch_assoc($result);
if ($row)
{
// Your result is here, as a big associative array. Each column in your
// table is now keyed to this array. Exact fields will depend on your DB.
//
// Just access it like something like this:
$id = $row['id'];
$time = $row['time_stamp'];
}
}
to echo it back out as JSON:
... // snip
if ($row)
{
header('application/json');
echo json_encode($row);
exit;
}
}
// handle your errors!
added: Additional error found in OP question:
// The following line isn't valid. This isn't what you'll get back from $.ajax.
// success: function(patientroom, patientname, eventtyp, timestamp)
// Corrected code:
success: function(data, textStatus, jqXHR)
/* called when request to getevents.php completes */
{
addevents(data.patientroom, data.patientname, data.eventtyp, data.timestamp);
setTimeout(
waitForEvents, /* Request next event */
1000 /* ..after 1 seconds */
);
},
Further updates. You mixed & matched the code from above.
$result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1");
if($result)
{
// this has to go inside of this check. This is where you *ASSIGN* $row.
$row = mysql_fetch_assoc($result);
// You need to rekey $row before you output:
$retVal = array('patientroom'=>$row['rumNr'],
'patientname'=>$row['inneboendeNamn'],
'eventtyp'=>$row['handelse'],
'timestamp'=>$row['timestamp']);
// I'm not sure what you're doing with the incoming timestamp. Should we just
// return it back out?
$retVal['ajax_timestamp'] = $_GET['timeStamp'];
header('application/json');
echo json_encode($retVal);
exit; // this exits. Comment this out if you want, but don't try to write anything else out to the buffer.
}
// Not sure what you're trying to do here. I'll comment out for now.
/*
$lastmodif = isset($_GET['timeStamp']) ? $_GET['timeStamp'] : 0;
$currentmodif = filemtime($result);
while($currentmodif <= $lastmodif)
{
unsleepp(1000);
clearstatcache();
$currentmodif = filemtime($result);
}
*/
}
I understand know that you shouldnt do long-polling with php. It's to messy if you aint a pro php-hacker and for many other reasons like:
PHP is made for fast execution (not for waiting)
PHP will force you to do some kind of polling on the server side and relying on sleep()
PHP will eat your RAM while so are spawning processes for each requests (Apache will do so)
The thing I need for my project is to show new data without refreshing the hole site. I did it like this:
<script type="text/javascript">
var timeoutId;
var intervalId;
function doIt(){
$("#main").load("refresh.php");
}
$(document).ready(function(){
timeoutId = setTimeout(function(){
doIt();
intervalId = setInterval(function(){
doIt();
}, 5000); //Request the doIt() method every 5ms.
}, 3000); //Delay calculated on the server to trigger the function at the appropriate time
});
</script>

Categories