I have a folder watcher that i want to be called once a minute, but i cant get it working.
The folder watcher will return 1 or 0. If data == 1 then the page will be refreshed, if 0 wait a min and run again.
Can someone help me to find out whats wrong?
The script:
<script type="text/javascript">
function timedRefresh(timeoutPeriod) {
setTimeout(Update(),timeoutPeriod);
}
function Update() {
$.ajax({
url: "checkfolder.php",
type: "POST",
success: function (data) {
if(data == "1"){
//Page will be updated
}
else{
timedRefresh(60000);
}
}
});
}
</script>
Heres the checkfolder.php:
<?php
// Configuration ///////////////////////////////////////////////////////////////
$host ='xxxx';
$port = 21;
$user = 'xxxx';
$pass = 'xxxx';
$remote_dir = '../img/uploads/';
$cache_file = 'ftp_cache';
// Main Run Program ////////////////////////////////////////////////////////////
// Connect to FTP Host
$conn = ftp_connect($host, $port) or die("Could not connect to {$host}\n");
// Login
if(ftp_login($conn, $user, $pass)) {
// Retrieve File List
$files = ftp_nlist($conn, $remote_dir);
// Filter out . and .. listings
$ftpFiles = array();
foreach($files as $file)
{
$thisFile = basename($file);
if($thisFile != '.' && $thisFile != '..') {
$ftpFiles[] = $thisFile;
}
}
// Retrieve the current listing from the cache file
$currentFiles = array();
if(file_exists($cache_file))
{
// Read contents of file
$handle = fopen($cache_file, "r");
if($handle)
{
$contents = fread($handle, filesize($cache_file));
fclose($handle);
// Unserialize the contents
$currentFiles = unserialize($contents);
}
}
// Sort arrays before comparison
sort($currentFiles, SORT_STRING);
sort($ftpFiles, SORT_STRING);
// Perform an array diff to see if there are changes
$diff = array_diff($ftpFiles, $currentFiles);
if(count($diff) > 0)
{
echo "1";//New file/deleted file
}
else{
echo "0";//nothing new
}
// Write new file list out to cache
$handle = fopen($cache_file, "w");
fwrite($handle, serialize($ftpFiles));
fflush($handle);
fclose($handle);
}
else {
echo "Could not login to {$host}\n";
}
// Close Connection
ftp_close($conn);
?>
just change
setTimeout(Update(),timeoutPeriod);
to
setTimeout(Update,timeoutPeriod);
setTimeout takes the function reference as the first parameter while you were passing the function call. You dont need the setInterval here as on receiving '0' you are already calling the refresh function.
You need to pass function reference to setTimeout, also need to use setInterval() as you need to invoke it every minute
function timedRefresh(timeoutPeriod) {
setInterval(Update,timeoutPeriod);
}
All you need to do is to put your function inside $(document).ready() and change your time out structure:
<script>
$(document).ready(function(){
setTimeout(function(){
Update()
},timeoutPeriod);
});
</script>
Try this one
$(document).ready(function(){
setInterval(function(){
//code goes here that will be run every 5 seconds.
$.ajax({
type: "POST",
url: "php_file.php",
success: function(result) {
//alert(result);
}
});
}, 5000);
});
Related
Is there a way to get updates from a PHP process while it's not finished and it has been called by ajax? By updates i mean flushed output from the PHP script.
var proc;
$('#start').click(function () {
proc = $.ajax({
type: 'POST',
url: 'execute.php',
// getData function that will get me updated data
getData: function (update){
alert(update);
}
});
});
UPDATE:
Lets say we want to get that echo before this ends.
execute.php
<?php
$progress = 0;
while(1){
$progress++;
echo $progress;
flush();
sleep(5);
if($progress == 100){
break;
}
}
?>
FINAL:
myScript.js
var strongcalcs;
var source;
$('#start').click(function () {
strongcalcs = $.ajax({
type: 'POST',
url: 'execute.php',
beforeSend: function () {
rpm_percent();
},
success: function(result){
source.close();
},
complete: function () {
source.close();
},
error: function () {
source.close();
}
});
});
function rpm_percent() {
source = new EventSource("execute.php");
if(typeof(EventSource) !== "undefined") {
source.onmessage = function(event) {
console.log(event.data);
};
} else {
alert("nono");
}
}
execute.php
<?php
$coco = 0;
function sendMsg($msg, &$coco) {
echo "id: " . $coco . "\n";
echo "data: " . $msg;
echo "\n";
echo "\n";
ob_flush();
flush();
$coco++;
}
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
$progress = 0;
while(1){
sendMsg($progress++, $coco);
ob_flush();
flush();
sleep(5);
if($progress == 100){
break;
}
}
?>
I've in the past used Server Sent Events for this (https://www.w3schools.com/html/html5_serversentevents.asp). Internet Explorer is not supported out of the box, but there are polyfills that can solve the issue.
I think Websockets do something similar but don't have experience with those myself.
you can use Ajax callback when success load file from server..
$('#start').click(function () {
proc = $.ajax({
type: 'POST',
url: 'execute.php',
success: function (respon){
//do what u want to do here.
if(respon.status == 0){
alert("failed");
}
else{
alert("ok");
}
},
error: function(xhr, error){
//for error handling
}
});
});
and in your php you can echo what u want to show
<?php
$var["status"] = 0;
//if(your condition){ $var["status"] = 1;}
return json_encode($var);
?>
for more information you can see on here and here
I would think this is simple but cannot figure it out for the life of me.. I want to refresh a div without refreshing everything.. I have a timer on each image that counts down from 24 hrs to 0 then disappears.. it all works but I cant seem to just refresh the timer div..
My php -
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$path = $row['path'];
$user = $row['user'];
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer <= 0){
}else{
echo '<img id="pic" src="/v2/uploads/'.$path.'"/>';
echo '<div id="user">#'.$user.'</div>';
echo '<div id="timer">'.$timer.' </div>';
}
}
}
I would like to refresh just the timer at 1 second intervals not the images.. I know I can use ajax to call it from an external file that loads all the content also as far as I know..Still new at this. *side not this is chopped up code for the example not all of it.
As per my comment, you could do something like this:
Add class "timer" to your #timer element (if you have more than one #timer element, use different ID for each element).
Create php script which returns new $timer whenever it's called:
ajax-timer.php
<?php
/* include file where $conn is defined */
$response = array();
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer > 0) {
//Add just timer to response array
$response[] = $timer;
}
}
}
//Return json response and handle it later in ajax:
echo json_encode(array(
'result'=>empty($response) ? 0 : 1,
'data'=>$response));
die();
Request data from ajax-timer.php with $.ajax and populate data when response is received:
timer-update.js
var ajaxTimerThread = 0;
var ajaxTimerRunning = false;
function ajaxTimerRun() {
//Prevent running function more than once at a time.
if(ajaxTimerRunning)
return;
ajaxTimerRunning = true;
$.post('ajax-timer.php', {}, function (response) {
ajaxTimerRunning = false;
try {
//Try to parse JSON response
response = $.parseJSON(response);
if (response.result == 1) {
//We got timer data in response.data.
for(var i = 0; i < response.data.length; i++) {
var $timer = $('.timer').eq(i);
if($timer.length) {
$timer.html(response.data[i]);
}
}
}
else {
//Request was successful, but there's no timer data found.
//do nothing
}
//Run again
ajaxTimerThread = setTimeout(ajaxTimerRun, 1000); //every second
}
catch (ex) {
//Could not parse JSON? Something's wrong:
console.log(ex);
}
});
}
$(document).ready(function() {
// Start update on page load.
ajaxTimerRun();
})
Toss your existing php code into a separate .php file
Then use a jquery method called load() to load that php file into your div.
$(document).ready(function() {
$("#div_ID_you_want_to_load_into").load("your_php_file.php");
var pollFrequency = function() {
if (document.hidden) {
return;
}
$("#div_ID_you_want_to_load_into").load('your_php_file.php?randval='+ Math.random());
};
setInterval(pollFrequency,18000); // microseconds, so this would be every 18 seconds
});
Now, within this code above is something is not needed, but can be helpful, and that is the if (document.hidden) {return;} which is basically a command to the browser that if the browser tab is not in-focus do not fire off the setInterval poll.
Also a good idea to keep in the randval= math stuff, just to make sure there is no caching.
I have an index.php page. The function of this page is infinite scrolling using AJAX, PHP and MySQL. The top portion contains PHP MySQL codes and bottom contains JavaScript.
I want to print the total number of rows in center of the page, but every time I try it shows "undefined variable" error.
I think when loading the page, the total number of variable tries to print first and then the PHP query takes place, so it shows "undefined variable", but when I put the total number of variable inside the PHP codings, there is no problem.
How can I prevent this?
My index.php is
//my php part here
<?php
if(isset($_POST["anotherID"])){
require_once("config.php");
$limit = (intval($_POST['limit']) != 0 ) ? $_POST['limit'] : 10;
$offset = (intval($_POST['offset']) != 0 ) ? $_POST['offset'] : 0;
$id = $_POST["anotherID"];
$query = $id;
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM x where title like '%xx%' ORDER BY rand() LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
$row_object = $DB->prepare("Select Found_Rows() as rowcount");
$row_object->execute();
$roww_object =$row_object->fetchobject();
$actual_row_count = $roww_object->rowcount;
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo'something';
}
}
$count = $actual_row_count;
exit;
}
?>
//my html part here
<html>
//some html codes
<?php echo $count; ?>
//some html codes here
//my java scripts here
<script type="text/javascript">
var busy = false;
var limit = 6
var offset = 0;
var anotherID = 5
function displayRecords(lim, off) {
$.ajax({
type: "POST",
async: false,
data: "limit=" + lim + "&offset="+ off+"&anotherID="+anotherID,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button"><div id="loader_image"><img src="loader.gif" alt="" width="24" height="24">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
//some html codes her
</html>
I know when a page is loading, the HTML parts are first loaded and then my jQuery stimulates the PHP part and then my results appear.
How can I fix this?
Why does $count always show "undefined variable"?
Thanks in advance.
You get an error of undefined $count because $count is defined only inside the if statement.
When the if clause doesn't apply $count is not defined.
Add an else clause to the if and initialize $count=0; and it will solve your problem.
Example:
....
$count = $actual_row_count;
exit;
}
else $count = 0;
?>
Question:
I have a php scraping function and code that all works well, however it times out because its trying to load 60 different pages...
I was thinking of using AJAX to load one page at a time in a loop. Since i'm very new to AJAX im having some trouble.
This is what I have so far, I can get it to loop through the links if I provide them, however I want it to scrape page 1, return the next page link and then scrape the next page on a continuous loop until there are no more pages. As it stands it goes into infinite loop mode...
Any ideas guys?
Here is my code which i took from a youtube video which was using an array (i am only passing through a string)
<?php
ini_set('display_errors',1);
//error_reporting(E_ALL);
set_time_limit(0);
require_once 'scrape_intrepid.php';
//posted to this page
if(isset($_POST['id'])) {
//get the id
$id = $_POST['id'];
//this returns the next page link successfully, i just cant get it back into the function
$ids = scrapeSite($id);
echo $ids;
echo "<br>";
$data = $id . " - DONE";
echo json_encode($data);
exit();
} else {
$ids = 'http://www.intrepidtravel.com/search/trip?page=1';
}
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
function update() {
ids = <?=json_encode($ids);?>;
if(ids){
var id = ids;
$.post("index.php",{id:id}).done(function(msg){
console.log(ids,msg);
update();
});
} else {
console.log("done");
$("#log").html("Completed!");
}
}
$("#go").click(function() {
$("#go").html("Loading...");
update();
});
});
</script>
</head>
<body>
<button id="go">Go button</button>
<div id="log">Results</div>
</body>
Ended up solving this in another way: The function I am calling to function.php runs the script and returns the next URL to scrape. which is the msg value, so the refresh is called again once this is validated. Just processed 60 pages each taking 38 seconds each :S
<script>
$(document).ready(function() {
refresh('http://www.intrepidtravel.com/search/trip?');
function refresh(url) {
$.ajax({
type: "GET",
url: "function.php",
data: 'url=' + url,
success: function(msg){
$('#result').append('--->Completed! <br>Next Page: is ' + msg);
console.log(msg);
if ($.trim(msg) == 'lastpage'){
$('#result').append('--->Last page - DONE!');
}
else {
refresh(msg);
}
}
}); // Ajax Call
} //refresh
}); //document.ready
</script>
And the function.php file:
require_once 'scrape_intrepid.php';
if ($_GET['url']){
$url = $_GET['url'];
if ($url=="lastpage"){
echo $url;
} else {
$nextlink = scrapeSite($url);
echo($nextlink);
}
}
I have a list of urls that I would like to open in a popup for say 10 seconds. So I click a button and it will open the first url then wait 10 seconds and play the next and so on until it's over.
I have found a few functions that I thought would work or help and I thought my logic was right and thought it should work but maybe someone with more knowledge can help me out. This is what I have:
<script type="text/javascript">
function Redirect(url) {
popupWindow = window.open(
url,'popUpWindow','height=481,width=858,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no')
}
function newPopup() {
<?php
$jsSql = mysql_query("SELECT * FROM `songs`");
while($jsRow = mysql_fetch_array($jsSql))
{?>
setTimeout('Redirect("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>")', 4000);
<?php
}
?>
}
</script>
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
?>
<script type="text/javascript">
function Redirect(url) {
window.open(url, 'popUpWindow', 'height=481,width=858,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no');
}
function newPopup() {
<?php
$stmt = $db->query("SELECT * FROM `songs`");
$songs = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($songs AS $index => $song) {
printf("setTimeout(Redirect('http://www.youtube.com/embed%s?autoplay=1'), 4000);", $song->url);
}
?>
}
// Start
newPopup();
</script>
Change
setTimeout('Redirect("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>")', 4000);
to
setTimeout(function() {
Redirect("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>")}, 4000);
would be a good start
I would do it like this:
var data = [];
var current = 0;
<?php
while($jsRow = mysql_fetch_array($jsSql))
echo "data.push($jsRow['url']);";
?>
function Redirect()
{
}
function newPopup()
{
Redirect(data[current]);
current++;
if (current < data.length)
setTimeout(function(){newPopup();}, 10*1000)
}
All you have to do is to call newPopup for the first time on some event. You mention button click.
The code also check if there are no more items to play.
The key to this issue is that after you open the popup window with the first URL, you then want to just set the window.location on the existing popup window so that it just loads a new URL. So, it would be something like this:
// globals
var songList;
function openNewPopup(url) {
return window.open(url, 'popUpWindow','height=481,width=858,left=10,top=10,
resizable=no,scrollbars=no,toolbar=no,menubar=no,
location=no,directories=no,status=no');
}
Then, for subsequent page loads into that existing popup window, you just
function setNewPopupURL(url, popup) {
popup.location = url;
}
I don't really know PHP, but you'd want to put the list of songs into a JS variable that you can later loop over:
// populate the songList
// the goal here is to do songList.push(songURL) for each song
// to add them all to the songList
<?php
$jsSql = mysql_query("SELECT * FROM `songs`");
while($jsRow = mysql_fetch_array($jsSql))
{?>
songList.push("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>");
<?php
}
?>
And, then you can start the popup rotation by calling a function like this:
function runPopup() {
var index = 0;
var popup = openNewPopup(songList[index++]);
function next() {
setNewPopupURL(songList[index % songList.length), popup);
++index;
setTimeout(next, 10*1000);
}
setTimeout(next, 10*1000);
}