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);
}
Related
I am creating a kind of messaging system with php and jQUERY, when you click on users profile and hit the messaging button it take us to the message page, it takes about 2sec to load previous message, so I added a code to scroll to bottom of the div class containing all message item once the ajax is loaded, to show latest messages , but the problem I am having is when I try to scroll up back I am having issues , the moment i try to scroll up due to the code i added it goes down on its own, any solution would be well appreciated.
Here is my JQ code - if there is anything else I can provide to help me solve this issue, I would do so quickly.
$(document).ready(function(){
/*post message via ajax*/
//get message
var c_id = $("#conversation_id").val();
//get new message every 2 second
setInterval(function(){
$(".display-message").load("get-message-ajax.php?c_id="+c_id , stateChange);
}, 2000);
});
function stateChange() {
var newstate = true;
if(newstate = true){
$(".conversation_history.clearfix").animate({
scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight
}, 1000)} else {
$(".conversation_history.clearfix").end();
var newstate = false;
}
}
Code from get_message-ajax.php
<?php
include 'db.php';
include 'function.php';
/*Get Message*/
if(isset($_GET['c_id'])){
$conversation_id = base64_decode($_GET['c_id']);
$querynew = "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'";
$mysqli_q_new = mysqli_query($connection, $querynew);
confirmQuery($mysqli_q_new);
if (mysqli_num_rows($mysqli_q_new) > 0 ){
while($user_real_info = mysqli_fetch_assoc($mysqli_q_new)){
$trap_user_from = $user_real_info['user_from'];
$trap_user_to = $user_real_info['user_to'];
$trap_user_message = $user_real_info['message'];
$querynew2 = "SELECT profile_image,firstname FROM `users` WHERE id='$trap_user_from'";
$mysqli_q_new2 = mysqli_query($connection, $querynew2);
confirmQuery($mysqli_q_new2);
$user_fetch = mysqli_fetch_assoc($mysqli_q_new2);
$user_form_username = $user_fetch['firstname'];
$user_form_img = $user_fetch['profile_image'];
?>
<div class='conversation_history_inner clearfix'>
<span><?php echo $user_form_username; ?> </span>
<div class='converstion_history_image img-is-responsive pull-left'>
<?php echo getUserImage($user_form_img) ?>
</div>
<div class='converstion_history_chat'>
<p><?php echo $trap_user_message; ?></p>
</div>
</div>
<?php
}
}
} else {
echo 'nth found';
}
?>
I'm assuming you only want to scroll down when it gets the first message. If so, I would suggest changing the stateChange function into this:
var scrolled = false;
function stateChange() {
if(!scrolled){
$(".conversation_history.clearfix").animate({scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight}, 1000);
scrolled = true;
}
}
This will make it only scroll down the first time it gets a new message instead of every time like it currently does.
The content is scrolling to bottom automatically because you have used setInterval function which will trigger at a constant interval of time. Use setTimeOut instead it will call only once after the specified time. Look here for more details
I got function that collects and display's all posts, and for each have upvote/downvote buttons.
On button click I call function called upvotePost and downvotePost.
It all works fine, but it refreshes page, I want to understand how to make it not-refresh page.
I know it's done by ajax/jquery, but don't understand how to make it.
My button example:
<a href="fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>">
Function calling:
if(isset($_GET['upvote-btn'])){
$fun->upvotePost();
}
And my function:
public function upvotePost(){
try
{
if(isset($_SESSION['user_session'])){
$user_id = $_SESSION['user_session'];
$stmt = $this->runQuery("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$user_id));
$myRow=$stmt->fetch(PDO::FETCH_ASSOC);
}else{
$_SESSION["error"]='Sorry, You have to login in you account!';
}
$id = $_GET['image_id'];
$user_id = $myRow['id'];
$stmt2 = $this->conn->prepare("SELECT count(*) FROM fun_post_upvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt2->execute();
$result2 = $stmt2->fetchColumn();
if($result2 == 0){
$stmt3 = $this->conn->prepare("INSERT INTO fun_post_upvotes (image_id,user_id) VALUES(:image_id,:user_id)");
$stmt3->bindparam(":image_id", $id);
$stmt3->bindparam(":user_id", $user_id);
$stmt3->execute();
$stmt4 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt4->execute();
$result4 = $stmt4->fetchAll();
foreach($result4 as $post){
$newUpvotes = $post['upvotes']+1;
$stmt5 = $this->conn->prepare("UPDATE fun_posts SET upvotes=$newUpvotes WHERE id=('$id')");
$stmt5->execute();
$_SESSION["result"]='You have succesfully liked this post!';
}
}else{
$_SESSION["error"]='You have already liked this post!';
}
$stmt6 = $this->conn->prepare("SELECT count(*) FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt6->execute();
$result6 = $stmt6->fetchColumn();
if($result6 > 0){
$stmt7 = $this->conn->prepare("DELETE FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt7->execute();
$stmt8 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt8->execute();
$result8 = $stmt8->fetchAll();
foreach($result8 as $post){
$newDownvotes = $post['downvotes'] - 1;
$stmt9 = $this->conn->prepare("UPDATE fun_posts SET downvotes=$newDownvotes WHERE id=('$id')");
$stmt9->execute();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Ajax is the perfect answer for your question. Please check out this. you may need to alter this snippet according to your requirement.
before doing this you should import jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
your upvote button should be like this,
<button id="upvote"> upvote </button>
add below snippet in your javascript section.
$(function(){
$("#upvote").click(function(){
$.ajax(
{ url: "fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>",
type: "get",
success: function(result){
// todo something you need to perform after ajax call
}
});
});
});
Basically you have to create a php file which will route the call(let's call it a controller) to the intended function. Then create an ajax function which will hit that controller. Have a look at
Ajax Intro
Or look at the Jquery Implementation
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);
});
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've searched everywhere for a method where a page can reload automatically for every x seconds without actually reloading the page's contents, I have php code(includes some html) which updates my database table whenever a new user joins the page. However this only works once.
PHP CODE
<?php
$userOn5 = "SELECT * FROM `usersOn` WHERE name = '$username'";
$query4 = mysql_query($userOn5) or die (mysql_error());
while ($row = mysql_fetch_array($query4)) {
// Gather all $row values into local variables for easier usage in output
$timenow = $row["time"];
}
$user = "SELECT * FROM `user`";
$query3 = mysql_query($user) or die (mysql_error());
while ($row = mysql_fetch_array($query3)) {
$usernow = $row["name"];
}
$secs = time() - $timenow;
mysql_query("UPDATE user SET name = '$user'");
if ($username == $usernow) {
?>
<div id="container" style="display:none;">
I've attempted using meta tag but that reloads the entire content, I've attempted moving the entire php code to a separate php file and tried loading it inside a div called 'show' in the page:
var auto_refresh = setInterval(
function ()
{
$('#show').load('registeruser.php').fadeIn("slow");
}, 10000); // autorefresh the content of the div after
//every 10000 milliseconds(10sec)
Basically what I'm trying to do is rerun the php code every 10 seconds. Help?
Quite likely your issue is due to browser cache. You can use the following workaround -- that's actually what ajax does when you use cache: false:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t);
$('#container').fadeIn("slow");
}, 10000);
});
UPDATE
Alternatively, you can use the following:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t).find('> div').fadeIn("slow");
}, 10000);
});