Jquery: Slide up div if last - php

I have this friend request page, and i want my div
echo "<div style=' font-weight: bold; background: #283b43; border-bottom: 1px dashed #719dab;'>";
echo "<img src='images/NewFriend_small.png' style='float: left; margin-left: 25px; margin-right: 10px;'>";
echo "Friend requests";
echo "</div>";
To disappear too if it's the last friend request the user have.
Right now it doesnt do it, and only slide up the actual request (username, picture and so)
How should i check for if its the last friendrequest?
Right now its my code is like this
$friendsWaiting = mysql_query("SELECT * FROM users_friends where uID = '$v[id]' AND type = 'friend' AND accepted = '0'");
while($showW = mysql_fetch_array($friendsWaiting)){
echo "id: $showU[bID]";
}
JS when they accept/deny friend:
function MeYouFriendNB(confirm){
var c = confirm ? 'confirm' : 'ignore';
var fID = $('#fID').val();
$.ajax({
type: "POST",
url: "misc/AddFriend.php",
data: {
mode: 'ajax',
friend: c,
uID : $('#uID').val(),
fID : $('#fID').val(),
bID : $('#bID').val()
},
success: function(msg){
$('#friend'+fID).slideUp('slow');
$('#Friendlist').prepend(msg);
$('#theNewFriend').slideDown('slow');
}
});
}

Use the :last selector in jQuery
http://api.jquery.com/last-selector/
$('div.friend:last').slideUp();
Is that what you were looking for?

Related

JQuery and PHP don't show all query results but some (randomly)

1st time asking here!
I have a MySQL SELECT query and array of results. I have a container and within that container I want to display child div(s) displaying the array result + JQuery to add some nice fadeIn and fadeOut. The issue is the script display some of the array but NEVER all. I have 7 but the page shows 5 sometimes even 2 only and the data seems to be picked randomly.
// Fetch user notifications
$stmt0 = $conn->prepare("SELECT notifid, notification FROM notifications WHERE userid = :userid AND username = :uname;");
$stmt0->execute(['userid' => $userid, 'uname' => $username]);
$results0 = $stmt0->fetchAll();
foreach ($results0 as $row0) {
$notifid = $row0['notifid'];
$notification = $row0['notification'];
$notificationid = substr(sha1(mt_rand()), 0, 8);
echo "<div class='bluenot' id='".$notificationid."'>✔ <b><i>$notification</i></b></div>";
echo '<script>
$(document).ready(function(){
var notifid = ' . $notificationid . ';
$("#notifybox").append($ (notifid) );
setTimeout(function() {
$(notifid).fadeIn("fast", function () { $(this).delay(5000).fadeOut("fast"); });
$(notifid).css("display", "block");});
});
</script>';
CSS :
.notifybox {
width: auto;
height: auto;
position: fixed;
bottom: 0;
left: 15px;
z-index: 1000 important;
}
.bluenot {
width: 400px;
height: 80px;
padding: 20px 40px 20px 40px;
margin-top: 8px;
margin-bottom: 8px;
display: none;
background: #aaa9ff;
border-left: #2933aa 10px solid;
border-radius: 10px;
color: #353759;
text-align: center;
}
SOLVED:
Made a copy of class .bluenot and named it .dbnot then changed the code to :
echo "<div class='dbnot' id='".$notificationid."'>✔ <b><i>$notification</i></b></div>";
echo '<script>
$("#notifybox").append($ (".dbnot") );
$(".dbnot").fadeIn( 800 ).delay( 1000 ).fadeOut( 400 ).$(".dbnot").css("display", "block");
</script>';
Hope this helps anyone who would face the same issue.
You are missing the closing curly brackets for your foreach loop but assuming you have it after your <script> block then i would guess you are over writing the variable "notifid"
I would try to rearrange your logic and if you are deadset on this approach then create the variable "notifid" with a another variable to avoid duplicate declarations
something maybe like
$(document).ready(function(){
var notifid_' . $notificationid . ' = ' . $notificationid . ';
$("#notifybox").append($ (notifid_' . $notificationid . ') );
setTimeout(function() {
$(notifid_' . $notificationid . ').fadeIn("fast", function () { $(this).delay(5000).fadeOut("fast"); });
$(notifid_' . $notificationid . ').css("display", "block");});
});

jquery - check database value every second

I am having problems with a jquery. The code below is not triggered when the php page loads. I attempt to check the value of a field in a database table and do a redirect if the returned value is 0. I have been struggeling with this for hours and I have really searched around to find the answer. Any help is appreciated.
<script type="text/javascript">
$jQn(document).ready(function(){
var do_checking;
var status = 1;
var ui = "";
if(status == 1){
$jQn.blockUI.defaults.overlayCSS.opacity=.3;
$jQn.blockUI({
message: ui,
css: {
border: '10px solid #888',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
color: '#fff',
width: '50%',
left: '25%',
cursor: 'wait',
'-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=10)',
'filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=10)',
'-moz-opacity':.10,
opacity:.10,
padding:'15px'
}
});
do_checking = setInterval(check_search_status, 1000);
} else {
document.location = 'https://mysite.com/result.php';
}
});
function check_search_status(){
$jQn.ajax({
type: 'POST',
url: 'https://mysite.com/checksearchstatus.php',
data: {
id: '$owner'
},
dataType: 'json',
success: function(response){
if(response.status == 0){
clearInterval(do_checking);
document.location = 'https://mysite.com/result.php';
}
}
});
}
</script>
Here is the code of the separated php file
$con = mysql_connect($db_host,$db_username,$db_password);
if (!$con)
{
die('Feil ved tilkobling av: ' . mysql_error());
}
mysql_select_db($db_name, $con);
$response = array('status' => '');
$user_id = $_POST['id'];
// Build SQL
$first_search_sql = "SELECT `firstsearch` FROM `class_users` WHERE id = '".$user_id."'";
$first_search_result = $db->query($first_search_sql);
// Fetch result
$first_search_row = $first_search_result->fetch();
// Free result
$first_search_result->freeResult();
$response['status'] = $first_search_row['firstsearch'] ;
echo json_encode($response);

jquery - multiple image upload form with remove option

I want some suggestions regarding image upload form like facebook and tumblr which can preview multiple images with caption and description fields with each image and if user wants to remove any image before uploading he is able to do that. So please suggest me how to achieve this i have tried this but i am having issue with removing image from input type = file as it is readonly i am facing problem when i am submitting the form on server. Please give me your ideas i really need help i have deadline of this month i am badly stuck in this problem. I am using php and jquery. Note: Please dont suggest any plugins.
Thanks in advance.
I have face same problem like you
now i have found solution for that i think this will be useful for you to solve your problem
<input type="file" id="attachfile" name="replyFiles" multiple> <!--File Element for multiple intput-->
<div id="#filelist"></div>
<script>
var selDiv = "";
var storedFiles = []; //store the object of the all files
document.addEventListener("DOMContentLoaded", init, false);
function init() {
//To add the change listener on over file element
document.querySelector('#attachfile').addEventListener('change', handleFileSelect, false);
//allocate division where you want to print file name
selDiv = document.querySelector("#filelist");
}
//function to handle the file select listenere
function handleFileSelect(e) {
//to check that even single file is selected or not
if(!e.target.files) return;
//for clear the value of the selDiv
selDiv.innerHTML = "";
//get the array of file object in files variable
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
//print if any file is selected previosly
for(var i=0;i<storedFiles.length;i++)
{
selDiv.innerHTML += "<div class='filename'> <span class='removefile' data-file='"+storedFiles[i].name+"'> " + storedFiles[i].name + "</span></div>";
}
filesArr.forEach(function(f) {
//add new selected files into the array list
storedFiles.push(f);
//print new selected files into the given division
selDiv.innerHTML += "<div class='filename'> <span class='removefile' data-file='"+storedFiles[i].name+"'> " + f.name + "</span></div>";
});
//store the array of file in our element this is send to other page by form submit
$("input[name=replyfiles]").val(storedFiles);
}
//This function is used to remove the file form the selection
function removeFile(e) {
var file = $(this).data("file"); //To take the name of the file
for(var i=0;i<storedFiles.length;i++) { //for find the file from the array
if(storedFiles[i].name === file) {
storedFiles.splice(i,1); //remove file from the list
break;
}
}
//now store the list of the all remaining file in our element name which will submit with the form
$("input[name=replyfiles]").val(storedFiles);
$(this).parent().remove();
}
$(document).ready(function(){
$("body").on("click", ".removefile", removeFile);
})
</script>
//I added event handler for the file upload control to access the files properties.
document.addEventListener("DOMContentLoaded", init, false);
//To save an array of attachments
var AttachmentArray = [];
//counter for attachment array
var arrCounter = 0;
//to make sure the error message for number of files will be shown only one time.
var filesCounterAlertStatus = false;
//un ordered list to keep attachments thumbnails
var ul = document.createElement("ul");
ul.className = "thumb-Images";
ul.id = "imgList";
function init() {
//add javascript handlers for the file upload event
document
.querySelector("#files")
.addEventListener("change", handleFileSelect, false);
}
//the handler for file upload event
function handleFileSelect(e) {
//to make sure the user select file/files
if (!e.target.files) return;
//To obtaine a File reference
var files = e.target.files;
// Loop through the FileList and then to render image files as thumbnails.
for (var i = 0, f; (f = files[i]); i++) {
//instantiate a FileReader object to read its contents into memory
var fileReader = new FileReader();
// Closure to capture the file information and apply validation.
fileReader.onload = (function(readerEvt) {
return function(e) {
//Apply the validation rules for attachments upload
ApplyFileValidationRules(readerEvt);
//Render attachments thumbnails.
RenderThumbnail(e, readerEvt);
//Fill the array of attachment
FillAttachmentArray(e, readerEvt);
};
})(f);
// Read in the image file as a data URL.
// readAsDataURL: The result property will contain the file/blob's data encoded as a data URL.
// More info about Data URI scheme https://en.wikipedia.org/wiki/Data_URI_scheme
fileReader.readAsDataURL(f);
}
document
.getElementById("files")
.addEventListener("change", handleFileSelect, false);
}
//To remove attachment once user click on x button
jQuery(function($) {
$("div").on("click", ".img-wrap .close", function() {
var id = $(this)
.closest(".img-wrap")
.find("img")
.data("id");
//to remove the deleted item from array
var elementPos = AttachmentArray.map(function(x) {
return x.FileName;
}).indexOf(id);
if (elementPos !== -1) {
AttachmentArray.splice(elementPos, 1);
}
//to remove image tag
$(this)
.parent()
.find("img")
.not()
.remove();
//to remove div tag that contain the image
$(this)
.parent()
.find("div")
.not()
.remove();
//to remove div tag that contain caption name
$(this)
.parent()
.parent()
.find("div")
.not()
.remove();
//to remove li tag
var lis = document.querySelectorAll("#imgList li");
for (var i = 0; (li = lis[i]); i++) {
if (li.innerHTML == "") {
li.parentNode.removeChild(li);
}
}
});
});
//Apply the validation rules for attachments upload
function ApplyFileValidationRules(readerEvt) {
//To check file type according to upload conditions
if (CheckFileType(readerEvt.type) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, You can only upload jpg/png/gif files"
);
e.preventDefault();
return;
}
//To check file Size according to upload conditions
if (CheckFileSize(readerEvt.size) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, The maximum file size for uploads should not exceed 300 KB"
);
e.preventDefault();
return;
}
//To check files count according to upload conditions
if (CheckFilesCount(AttachmentArray) == false) {
if (!filesCounterAlertStatus) {
filesCounterAlertStatus = true;
alert(
"You have added more than 10 files. According to upload conditions you can upload 10 files maximum"
);
}
e.preventDefault();
return;
}
}
//To check file type according to upload conditions
function CheckFileType(fileType) {
if (fileType == "image/jpeg") {
return true;
} else if (fileType == "image/png") {
return true;
} else if (fileType == "image/gif") {
return true;
} else {
return false;
}
return true;
}
//To check file Size according to upload conditions
function CheckFileSize(fileSize) {
if (fileSize < 300000) {
return true;
} else {
return false;
}
return true;
}
//To check files count according to upload conditions
function CheckFilesCount(AttachmentArray) {
//Since AttachmentArray.length return the next available index in the array,
//I have used the loop to get the real length
var len = 0;
for (var i = 0; i < AttachmentArray.length; i++) {
if (AttachmentArray[i] !== undefined) {
len++;
}
}
//To check the length does not exceed 10 files maximum
if (len > 9) {
return false;
} else {
return true;
}
}
//Render attachments thumbnails.
function RenderThumbnail(e, readerEvt) {
var li = document.createElement("li");
ul.appendChild(li);
li.innerHTML = [
'<div class="img-wrap"> <span class="close">×</span>' +
'<img class="thumb" src="',
e.target.result,
'" title="',
escape(readerEvt.name),
'" data-id="',
readerEvt.name,
'"/>' + "</div>"
].join("");
var div = document.createElement("div");
div.className = "FileNameCaptionStyle";
li.appendChild(div);
div.innerHTML = [readerEvt.name].join("");
document.getElementById("Filelist").insertBefore(ul, null);
}
//Fill the array of attachment
function FillAttachmentArray(e, readerEvt) {
AttachmentArray[arrCounter] = {
AttachmentType: 1,
ObjectType: 1,
FileName: readerEvt.name,
FileDescription: "Attachment",
NoteText: "",
MimeType: readerEvt.type,
Content: e.target.result.split("base64,")[1],
FileSizeInBytes: readerEvt.size
};
arrCounter = arrCounter + 1;
}
/*Copied from bootstrap to handle input file multiple*/
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
/*Also */
.btn-success {
border: 1px solid #c5dbec;
background: #d0e5f5;
font-weight: bold;
color: #2e6e9e;
}
/* This is copied from https://github.com/blueimp/jQuery-File-Upload/blob/master/css/jquery.fileupload.css */
.fileinput-button {
position: relative;
overflow: hidden;
}
.fileinput-button input {
position: absolute;
top: 0;
right: 0;
margin: 0;
opacity: 0;
-ms-filter: "alpha(opacity=0)";
font-size: 200px;
direction: ltr;
cursor: pointer;
}
.thumb {
height: 80px;
width: 100px;
border: 1px solid #000;
}
ul.thumb-Images li {
width: 120px;
float: left;
display: inline-block;
vertical-align: top;
height: 120px;
}
.img-wrap {
position: relative;
display: inline-block;
font-size: 0;
}
.img-wrap .close {
position: absolute;
top: 2px;
right: 2px;
z-index: 100;
background-color: #d0e5f5;
padding: 5px 2px 2px;
color: #000;
font-weight: bolder;
cursor: pointer;
opacity: 0.5;
font-size: 23px;
line-height: 10px;
border-radius: 50%;
}
.img-wrap:hover .close {
opacity: 1;
background-color: #ff0000;
}
.FileNameCaptionStyle {
font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div>
<label style="font-size: 14px;">
<span style='color:navy;font-weight:bold'>Attachment Instructions :</span>
</label>
<!--To give the control a modern look, I have applied a stylesheet in the parent span.-->
<span class="btn btn-success fileinput-button">
<span>Select Attachment</span>
<input type="file" name="files[]" id="files" multiple accept="image/jpeg, image/png, image/gif,"><br />
</span>
<output id="Filelist"></output>
</div>

jquery draggable list position save to database

i have following code for get data from database and sort draggable list using jquery ui elements.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; background-color:#CCC;}
#sortable li span { position: absolute; margin-left: -1.3em; }
</style>
<script>
$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
});
</script>
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = $_SESSION['user_id'];
$result = mysqli_query($con,"SELECT * FROM users WHERE user_id = '$user_id'");
echo "<ul id='sortable'>";
while($row = mysqli_fetch_array($result))
{
echo "<li class='ui-state-default'>" . $row['Name'] . ' ' . $row['UserName'] . $row['sort'] ."</li>";
}
echo "</ul>";
mysqli_close($con);
?>
This is my database table structure
Table Name = users
Columns = user_id, Name, UserName, Password, sort
Example Results
user_id Name UserName Password sort
1 AAA aa *** 1
2 BBB bb *** 2
3 CCC cc *** 3
4 DDD dd *** 4
what i am asking is, i can Reorder list items by using jquery draggable properties, but how can i save sort number to database if reordered list items.?
jQuery UI sortable has a stop callback which is called when you stop moving a sortable. It also has a serialize function that you can use in combination to send the order of your sortables to your to the process which updates your database. You can use it like this:
To use serialize you need to amend your sortable element in the DOM so that it contains a reference to the user_id. E.g.
<li class="ui-state-default" id="id_<?php echo $row['user_id'] ?>">...</li>
Then when you serialize the sortable, it will build a list of parameters. You don't have to use the id attribute to reference your data, read more about the serialize method here. But below is an example of how you can do it using the id attribute
var $sortable = $( "#sortable" );
$sortable.sortable({
stop: function ( event, ui ) {
// parameters will be a string "id[]=1&id[]=3&id[]=10"...etc
var parameters = $sortable.sortable( "serialize" );
// send new sort data to process
$.post("/sort/my/data.php?"+parameters);
}
});
You then need a process that receives this data and updates the database. I'll leave most of this up to you, but here's a minimal example.
<?php
// Store user IDs in array. E.g. array(0 => "1", 1 => "3", 2 => "10"....)
$userIds = $_POST['id'];
// Connect to your database
$conn = mysqli_connect("localhost","root","","db_name");
foreach ($userIds as $key => $userId) {
$sequence = $key + 1;
$stmt = $conn->prepare("UPDATE users SET sort = $sequence WHERE user_id = ?");
$stmt->bind_param("i", (int) $userId);
$stmt->execute();
}
$stmt->close();

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