JavaScript setInterval() not showing contents? - php

My javascript code isn't working. I went to the page and it was displaying the content. Why isn't it appending the data to .userStats? invest_process.php contains the information that grabs the values shown in the PHP. That's not what would be causing the issue. Thanks, code below.
HTML Code:
<div id="content1" class="tabscontent">
<p>
<span class="userStats"></span>
</p>
</div>
JavaScript:
<script type="text/javascript">
var auto_refresh_stats = setInterval(
function (){
$('.userStats').load('get_user_stats.php').show();
}, 1000 );
</script>
PHP Code:
<?php
require 'invest_process.php';
echo
'<span><h3>You have:
' . $select_invested['amtInvested'] .
' Invested in GigaDice | You have:
' . $select_invested['amtInvested']/$select_invested_total['siteInvested']*100 .
' % of the site\'s bankroll</span></h3> <span><h3> You have
' . $select_balance_gg['gigagold'] .
' in GG Balance | You have profitted:
' . $siteProfit*$select_invested['amtInvested']/$select_invested_total['siteInvested'] .
'</span></h3>';
?>

Add $(document).ready() block
$(document).ready(function()
{
var auto_refresh_stats = setInterval(
function ()
{
$('.userStats').load('get_user_stats.php').show(); // if you want to replace
}, 1000 );
});
If you want to append the contents then use the following
$('.userStats').append($('<div>').load('get_user_stats.php'));

try this
<script type="text/javascript">
var auto_refresh_stats = setInterval(
function (){
$('.userStats').load('get_user_stats.php');
}, 1000 );
</script>

Related

Jquery Update DIV with rsync progress

I'm trying to update a DIV with the ongoing output from an rsync command. The idea being I can see how the download is progressing.
This is the code I've got, but I'm getting errors relating 'Uncaught SyntaxError: Unexpected token ILLEGAL'
<?php
$down = popen('rsyncd -Pav http://ipv4.download.thinkbroadband.com/1GB.zip 1GB.zip', 'r');
while($progress = fgets($down, 124)) {
ob_flush();flush();
?>
<script type="text/javascript">
$(document).ready(function() {
var update = "<?php echo $progress; ?>";
$("#status").html(update);
});
</script>
<?php
ob_flush();
ob_flush();flush();
}
pclose($down);
}
?>
<div id="status"></div>
In the console I can see that it relates to :
var update = " 33390592 46% 4.62MB/s 0:00:08
34701312 48% 4.63MB/s 0:00:07
35979264 50% 4.63MB/s 0:00:07
";
How can I get each line of update and show it in a DIV without getting errors ?
Thanks
UPDATE
I'm now using this. The php echo for $update shows the output live in the web page, but the DIV is not updated until the page completes and then I only get the last line of output.
Why does the php echo work, but the jquery update to the div now work as expected ?
<?php
$down = popen('rsyncd -Pav http://ipv4.download.thinkbroadband.com/1GB.zip 1GB.zip', 'r');
$order = array("\r\n", "\n", "\r");
while($progress = fgets($down, 32)) {
ob_flush();flush();
$update = str_replace($order,'<br />', $progress);
echo $update; // <-- this outputs fine.
?>
<script type="text/javascript">
$(document).ready(function() {
var update = "<?php echo $update; ?>";
$("#status").html(update);
});
</script>
<?php
ob_flush();flush();
}
pclose($down);
}
?>
Is this due to the jquery not running until the page is fully loaded, so the div is only updated with the last entry of $update ?
If so is there any way to have the jquery run as the page is loading so the DIV is updated ?
Thanks :)
Thanks
UPDATE
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
$("#test").click(function () { $("#log").load("go.php"); });
});
</script>
Just tried the above, it works and calls go.php and I get the output but only when go.php has finished the rsync download. any way to show the ongoing output whilst the download happens ?
use str_replace() php function
<?php
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
?>
<script type="text/javascript">
$(document).ready(function() {
var update = "<?php echo str_replace($order, $replace, $progress); ?>";
$("#status").html(update);
});
</script>

Delete clicked item in jQuery and PHP?

I just have a quick question how do I delete the item I just clicked? I don't have a great way of tracking it and I'm at my last resort way right now (which is what I'm posting) which deletes everything in the list.
PHP/HTML/jQuery:
<div class="image-list">
<?php
$count = 1;
if ($hotelId) {
foreach(glob($hotelDir) as $filename=>$hotelvalue){
echo '<li id="del'.$count.'" class="image-list"><a class="enlargeUser" href="'.$hotelvalue.'"><img class="imageListMain" src="'.$hotelvalue.'" width="50px" height="50px"/><p class="filename">' . basename($hotelvalue) . '</p></a> <a class="btn btn-mini btn-primary image-list" style="width: 18px;margin-top: -35px;position: relative\9;top: -25px\9;border-radius: 100%;-moz-border-radius: 100%;-o-border-radius: 100%;-webkit-border-radius: 100%;margin-left:330px;" id="del'.$count.'" value="Delete"><i class="icon-remove-circle icon-2" style="margin-left:-3px;"></i></a></li>' . "\n" . "<br>";
$count++;
}
}else{}
?>
</div>
</div>
<script>
$('div.image-list li a.image-list').live('click', function() {
bootbox.confirm("Are you sure you want to delete this image?", "Cancel", "Confirm", function(result) {
if (result) {
$('ul.image-list li a.image-list').closest('li').fadeOut();
$.post('assets/php/deletefile.php');
}
});
});
</script>
Here is the delete information (right now it is static PHP that only deletes the first file I don't have another way of doing this yet):
<?php
session_start();
$files = glob("upload/" . $_SESSION['curHotelId'] . "/" . '*.*');
if(is_file($files[0]))
#unlink($files[0]);
?>
UPDATE:
Thanks to Karl's answer I got a better idea of what I'm doing, but I still cannot get these to remove. I don't know why. They stay blank and act as if they don't even exist or the button does not work.
Here is my updated PHP/HTML/jQuery:
<div class="image-list">
<?php
$count = 1;
if ($hotelId) {
foreach(glob($hotelDir) as $filename=>$hotelvalue){
echo '<li data-filename="' . basename($hotelvalue) . '" id="del'.$count.'" class="image-list"><a class="enlargeUser" href="'.$hotelvalue.'"><img class="imageListMain" data-filename="' . basename($hotelvalue) . '" src="'.$hotelvalue.'" width="50px" height="50px"/><p class="filename">' . basename($hotelvalue) . '</p></a> <a data-filename="' . basename($hotelvalue) . '" class="btn btn-mini btn-primary image-list" style="width: 18px;margin-top: -35px;position: relative\9;top: -25px\9;border-radius: 100%;-moz-border-radius: 100%;-o-border-radius: 100%;-webkit-border-radius: 100%;margin-left:330px;" id="del'.$count.'" value="Delete"><i class="icon-remove-circle icon-2" style="margin-left:-3px;"></i></a></li>' . "\n" . "<br>";
$count++;
}
}else{}
?>
</div>
</div>
<script>
$('li.image-list a.image-list').click( function () {
var filename = $(this).attr('data-filename');
$(this).remove();
$.get('assets/php/deletefile.php?filename=' + filename).done( function() {
// it succeeded
}).fail( function (){
// it failed
});
});
});
</script>
And the PHP was updated too:
<?php
session_start();
$filename = $_get['filename'];
$files = glob("upload/" . $_SESSION['curHotelId'] . "/" . $filename);
if(is_file($files))
#unlink($files);
?>
HOPEFULLY FINAL UPDATE:
I'm so close, I just wanna throw everything I love out a window. So here is where I'm having an issue. It isn't deleting the images when the code executes so here is PHP:
ALL OF THIS CODE WORKS. C: Thank you everyone that helped!
<?php
session_start();
$file = $_POST['filename'];
$selHotelId = $_SESSION['curHotelId'];
$files = "upload/" . $selHotelId . "/" . $file;
unlink($files);
?>
jQuery:
$(document).ready(function(){
$("#imageClick").live("click", "li.image-list a.image-list", function () {
var _clicked = $(this);
var _filename = _clicked.attr('data-filename');
_clicked.parents("li.image-list").fadeOut(function(){
$(this).empty().remove();
});
$.post('assets/php/deletefile.php', {filename: _filename}).done( function(data) {
bootbox.alert('File has been deleted!');
}).fail( function (error){
bootbox.alert('There has been an error. Contact admin.');
});
});
});
There were still a few issues in your updated code. I've made some changes, and pasted in the code below. I've changed the method to $.post(), so your PHP file will need to access the parameter as $_POST['filename'].
A couple issues I noticed, you had more than one element with the same id attribute. I removed the redundant data-filename attributes from elements that didn't need them. I placed your jQuery inside a $(document).ready() in order to make sure that nothing was called until all DOM elements had been loaded. I also used the .on method for binding the event...just in case you ever dynamically add more li elements with the a.image-list element. This way you are binding the event to an element that will always be there, and catching it on the a.image-list. (I might be explaining that incorrectly...it's late).
Hope this helps.
<ul class="image-list">
<?php
$count = 1;
if ($hotelId) {
foreach(glob($hotelDir) as $filename=>$hotelvalue){
echo '<li id="del'.$count.'" class="image-list"><a class="enlargeUser" href="'.$hotelvalue.'"><img class="imageListMain" src="'.$hotelvalue.'" width="50px" height="50px"/><p class="filename">' . basename($hotelvalue) . '</p></a> <a class="btn btn-mini btn-primary image-list" style="width: 18px;margin-top: -35px;position: relative\9;top: -25px\9;border-radius: 100%;-moz-border-radius: 100%;-o-border-radius: 100%;-webkit-border-radius: 100%;margin-left:330px;" title="Delete" data-filename="' . basename($hotelvalue) . '" ><i class="icon-remove-circle icon-2" style="margin-left:-3px;"></i></a></li>' . "\n" . "<br>";
$count++;
}
}
?>
</ul>
<script>
$(document).ready(function(){
$("ul.image-list").on("click", "li.image-list a.image-list", function () {
var _clicked = $(this);
var _filename = _clicked.attr('data-filename');
_clicked.parents("li.image-list").fadeOut(function(){
$(this).empty().remove();
});
$.post('assets/php/deletefile.php', {filename: _filename}).done( function(data) {
// it succeeded
}).fail( function (error){
// it failed
});
});
})
</script>
UPDATE: I had a typo in my code...not sure you caught it.
var _filename = clicked.attr('data-filename');
SHOULD BE...
var _filename = _clicked.attr('data-filename');
My apologies.
To see if you are hitting your PHP file, you can do something simple like this...
<?php
$data["response"] = $_POST['filename'];
echo json_encode($data);
?>
And then modify your .done method to look like this...
$.post('assets/php/deletefile.php', {filename: _filename}).done( function(data) {
// it succeeded
console.log(data);
}).fail( function (error){
// it failed
});
You can delete or remove a DOM element with jQuery using a syntax similar to this and pull the value passed in your item:
$('div.image-list li a.image-list').click( function () {
var filename = $(this).attr('data-filename');
$(this).parents('li').remove();
});
You will have pass the data to the PHP file like you are doing but with the filename in the url:
$.get('assets/php/deletefile.php?filename=' + filename).done( function() {
// it succeeded
}).fail( function (){
// it failed
});
When you load the page you will have to load in the data-filename="filename.jpg" into the element you clicked.
In your deletefile.php, you can use $_GET['filename'] to get the filename.

Download-Page with JQuery request

I have a download page. Members are free to click on their bought songs and the download starts. I wish now that in the same time an Ajax request takes place, which adjusts the count of downloads in the database. The page should then be reloaded to the counter from the database is updated again. If the counter is zero, there is no longer downloading.
Obviously my script does not work. The download happens, but the JQuery-Script will not work. Does someone have a solution?
This is the link to the download-page:
<a href="get-download-files.php?file=xyz.zip"><img class="a_0" src="images/download.png" width="30" height="30" />XYZ-Song/a>
And this is the Java-Script on the same page:
<script>
$(document).ready(function(){
$(".a_0").click(function(){
$.get("zaehler.php?dl_id=1", function(data){
$("#ausgabe").html(data);
});
});
});
</script>
And this is the request-file:
<?php
require_once 'includes/db_login.php';
$dl_id = $_REQUEST['dl_id'];
// counter updaten
$sql = 'UPDATE ' . $tbl_prefix . 'downloads
SET zaehler = zaehler - 1
WHERE dl_id = ' .$dl_id;
mysql_query($sql);
$abfrage = 'SELECT zaehler FROM ' . $tbl_prefix . 'downloads WHERE dl_id=' . $dl_id;
$ergebnis = mysql_query($abfrage);
while ($datensatz = mysql_fetch_array($ergebnis, MYSQL_ASSOC))
{
echo '<h3 style="color:#333;">Dein Download-Stand</h2>';
echo '<br /><br />Du hast noch ' . $datensatz['zaehler'] . ' Downloads zugut.';
}
?>
Im thanking you. Best regards,
Heinz
You don't need Ajax for this. In the script get-download-files.php, update the database before delivering the file to the browser.
Have you tried this?
<script>
$(document).ready(function(){
$(".a_0").click(function(){
$("#ausgabe").load("zaehler.php?dl_id=1");
});
});
</script>
You can check if your code is executed by adding a alert() inside your function. If the alert fires, the function is executed.
<script>
$(document).ready(function(){
$(".a_0").click(function(){
alert('Function is fired!'); // Debug
$("#ausgabe").load("zaehler.php?dl_id=1");
});
});
</script>

Ajax reloading a PHP-Page that shows HTML-Canvas altered by Javascript not working

so I have a Ajax-Scripts thats permanently reloads a PHP-Page:
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
loadstatus();
});
function loadstatus(){
$.ajax("innopbx.monitor.php").done(function(data){
document.getElementById("status").innerHTML = data;
setTimeout('loadstatus()', 1000);
});
}
</script>
And the PHP-Page being reloaded shows HTML-Canvas like this:
echo '<canvas id="' . $ui->guid . '" width="100" height="100" class="clear" style="border:1px dotted"></canvas> ';
echo '<script type="text/javascript">
var a_canvas = document.getElementById("' . $ui->guid . '");
var a_context = a_canvas.getContext("2d");
var gradient = a_context.createLinearGradient(0, 0, 0, 100);
gradient.addColorStop(0, "#bbffbb");
gradient.addColorStop(1, "#55ff55");
a_context.fillStyle = gradient;
a_context.fillRect(2, 2, 96, 96);
a_context.font = "10px sans-serif";
a_context.fillStyle = "black";
a_context.fillText("' . $ui->cn . '", 5, 20);
</script>';
When I navigate to the PHP-Page directly the Canvas is drawn exactly as expected. But when I navigate to the Page with the AJAX-Function that reloads the PHP-Page permanently I only see the dotted border. Its not filled and no Text is there.
Do you have any idea? Thanks in advance!
You can try to add document.getElementById("status") as target parameter of $.ajax.
var t = document.getElementById("status");
function loadStatus(){
$.ajax({url: "innopbx.monitor.php", target: t, success: function(){
setTimeout(loadstatus, 1000);
});
}
It should deal with the js execution, rather than innerHTML = ....

Pass a php var to jQuery Function

How do I pass a variable in a php file that is loaded into a page (DOM) to a jQuery function??
Iv'e tried various method's while searching online but I haven't figured out how to use them correctly.
I need the var navHeaderTitle to be passes to the jQuery load() callback function so it sets the HTML tag, #navHeaderTitle, to the variable called in the php file.
Thnx for you help.
php:
<?php
$con = mysql_connect("localhost","user","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM some_list");
$navHeaderTitle = "MY NEW TITLE";//<--I NEED 2 INJECT THIS!!
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='$navHeaderTitle'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
JavaScript in the HTML Head:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function() {
$('#navHeaderTitle').text($(html).find('div#navItem').attr('title'));//<--GET THE VAR FROM LOADED PHP FILE!!
});
});
</script>
<body>
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>//THIS IS WHAT NEEDS THE VAR DATA!!
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">HTML CONTENT from PHP GETS DUMPED IN HERE</div>
</div>
</div>
</body>
Ive tried using this but not sure how to:
$.get('scripts/my_list.php', {}, function(data){
data = split(':');
})
I would have the php file return a json object that contains two parts, the html you want to echo and the title you want to use.
Then I would use jQuery's .ajax() function instead of .load() to get the return value from your php script in a javascript variable instead of dumping it directly as .load() does.
replace echo("$navHeaderTitle"); with
echo("<script> var navHeaderTitle = $navHeaderTitle </script>");
and remove var navHeaderTitle = ''; from the <head> script..
that will setup a JS variable like you're using, but you have to do that before the code in the <head> loads...
EDIT
ok don't echo("$navHeaderTitle"); you can put it into the HTML like:
echo "<div id='navItem' title='$navHeaderTitle'>";
then in the JS you can do:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function(response) {
$('#navHeaderTitle').text($(response).attr('title'));
});
});
</script>
here's a jsfiddle demo: http://jsfiddle.net/JKirchartz/hdBzF/ (it's using fiddle's /echo/html/ so the load has some extra stuff to emulate the ajax)
It would be cleaner to pass the var in a custom attribute (data-var), then fetch it width JQuery
$(some_element).attr("data-var");
I hate to mess my JS code with php.

Categories