0

as the title says, is it possible to refresh a div without another html or php page inside of the div?

for example this is what can be done using javascript:

  $(document).ready(function () {
     $('#mydiv').delay(10000).load('page.php');
  });

My Div shows/holds a data which is pulled from the mysql database and it doesn't have page.php inside it.

I've searched for this and all the results were similar to the one i posted above!

is this even possible and if so how?

EDIT:

the data that currently is displayed in the DIV is the $end_time for an item. the $end_time is basically a datetime which is stored in the mysql database. the $end_time already is ticking (a countdown timer using javascript). There is button which whenever pressed, 1 minute Will be added to the $end_time in the mysql.

But when the button is pressed I need to refresh/re-load the page in order to be able to view the changes (in this case 1 minuted added to the countdown timer).

what I need to do is to reload the DIV once that button is pressed so all the users can see that 1 minute has been added to the countdown timer WITHOUT reloading or refreshing the page.

EDIT:

Here is my full code, this works as it should and it will pull the data from mysql database as it should so I have no problem with this part of the project:

<?php 
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('Europe/London'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database  
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){ 
             $id = $row["id"];
             $product_name = $row["product_name"];
             $date_added = date("Y-m-d", strtotime($row["date_added"]));
             $end_date = date("F d Y H:i:s T", strtotime($row["end_date"]));
             $price = $row["price"];
             $dynamicList .= '<div>' . $end_date . '
      </div>';
    }
} else {
    $dynamicList = "No Records";
}
?>

<?php
$date = $end_date;
$exp_date = strtotime($date);
$now = time();

if ($now < $exp_date ) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time

var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;

function showRemaining()
{
    var now = new Date();
    var distance = end - now;
    if (distance < 0 ) {
       clearInterval( timer );
       document.getElementById('countdown').innerHTML = 'EXPIRED!';

       return;
    }
    var days = Math.floor(distance / _day);
    var hours = Math.floor( (distance % _day ) / _hour );
    var minutes = Math.floor( (distance % _hour) / _minute );
    var seconds = Math.floor( (distance % _minute) / _second );

    var countdown = document.getElementById('countdown');
    countdown.innerHTML = '';
   if (days) {
        countdown.innerHTML += 'Days: ' + days + '<br />';
    }
    countdown.innerHTML += 'Hours: ' + hours+ '<br />';
    countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
    countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}

timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
    echo "Times Up";
}
?>
<div id="result"><div id="countdown"></div></div>

<?php echo $end_date; ?> </br>


<?php echo $dynamicList; ?>

<script src="ajax_link.js" type="text/javascript"></script>


<div id="ajaxlink" onclick="loadurl('timeadder.php')">Click here</div>


<input type="submit" name="ajaxlink" id="ajaxlink" value="Submit" onclick="loadurl('timeadder.php')"/>

and Here is the code for the page that will add the 1 minute to the database and this owrks fie as it should too:

timeadder.php

<?php 
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>

<?php

session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database  
include "config/connect.php";
$sql = "UPDATE item SET end_date = DATE_ADD(end_date,INTERVAL 1 MINUTE) WHERE id = 1;";

$query = mysqli_query($db_conx, $sql);


?>

All i need to do is to refresh the DIV countdown that holds the timer.

I hope someone now can help.

  • Of course it's *possible.* You'll need new code and a new server-side script to update it, though. – Blazemonger Sep 19 '13 at 15:05
  • Slightly confused - do you mean like `$('#mydiv').text('...');` or `$('#mydiv').html('...');` or something else? – CompanyDroneFromSector7G Sep 19 '13 at 15:07
  • @bukko, sorry for the confusion. what i mean is like this, I have a div which will show a countdown timer. the countdown timer is pulled from mysql database. there is a button that if pressed it will add 1 minute to the mysql database field. Now, i need to refresh that DIV every second in case someone has pressed the button so everyone can see the added minute to the current time. – EnergyLynx EnergyLynx Sep 19 '13 at 15:11
  • 1
    So you need to make an Ajax post to the server with the refreshed time. Once per second is a lot of ajax though! – CompanyDroneFromSector7G Sep 19 '13 at 15:12
  • 1
    @EnergyLynxEnergyLynx .. you can not do this with div i think .. but you can make a ajax call or you can use iframe – Dhaval Sep 19 '13 at 15:16
  • @EnergyLynxEnergyLynx I was in the process of posting more, saying that you don't need `addval` (which was the amount of time to be added to the enddate -- basically, I didn't fully understand what you were doing and allowed for user to specify any value). Now that I see what you are doing, I suspect that you must update the enddate on a `per-item` basis -- in other words, you also need to specify which item to add the extra minute to. Right? If so, then you **do** need to send some info to the server -- not the num_minutes, but the **item_id**. – cssyphus Sep 19 '13 at 16:48

4 Answers4

1

The question is unclear, but if your were trying to periodically load a php into a div it could be done with setInterval

setInterval(
   function(){
       $('#mydiv').load('page.php');
  },10000);

EDIT:

Ok then Id suggest Jquery.get

setInterval(function(){
  $.get('page.php',function(timerValue){
     $('#mydiv').html(timerValue);
   });
 },1000);
andrew
  • 9,313
  • 7
  • 30
  • 61
  • I have already said I don't want to load another page inside of the DIV. otherwise my own code above works fine. sorry for the confusion though. i've explained it a bit better above. – EnergyLynx EnergyLynx Sep 19 '13 at 15:13
  • The one thing that I don't understand is that what if the `page.php` is the same page that I have the `#mydiv` on? would it still work? – EnergyLynx EnergyLynx Sep 19 '13 at 16:00
  • I can answer my own question. Nope. as i tested it and it will duplicate the page.php inside the div. – EnergyLynx EnergyLynx Sep 19 '13 at 16:02
  • @EnergyLynxEnergyLynx in the above example, no, page.php should output the timer value and thats all, it is possible to use the same page by reading a request parameter in the php, eg `if(isset($_REQUEST['isAjax']))` but i find it easier to use a separate page – andrew Sep 19 '13 at 16:04
  • @EnergyLynxEnergyLynx Note that $.get() *is* AJAX. `$.get()` and `$.post()` are forms of `$.ajax()` with the `type="GET"` and `type="POST"` hard-coded. I recommend using `$.ajax()` as in my examples, as the formalized structure is easier to manage, especially as a beginner. – cssyphus Sep 19 '13 at 16:26
  • @gibberish, i would use your example as long i understand it but I am so cunfused its unreal. – EnergyLynx EnergyLynx Sep 19 '13 at 16:31
  • 2
    @EnergyLynxEnergyLynx Hang with us, buddy. We'll get you through this. When this problem is solved, do yourself a favor and run through a few AJAX examples, like the simple examples I posted. AJAX is ... well, how have you lived without it? (you will say)... – cssyphus Sep 19 '13 at 16:41
1

Modified to integrate newly posted code in OP:

In your while{} statement, you are sticking div tags around the end date, but there is no easy way to identify which item's end date the div belongs to.

Suggestion:

$dynamicList .= '<div id="ed-' .$id. '">' . $end_date . '</div>';

That will create a uniquely named div around each end date. Now, you can access a specific end date via jQuery, thus:

$('#ed-3').html(newdata);

Also, shouldn't this:

<div id="result"><div id="countdown"></div></div>
<?php echo $end_date; ?> </br>

Be like this:

<div id="result"><div id="countdown"><?php echo $end_date; ?></div></div>
</br>

HTML:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        
        <script type="text/javascript">
        
            var item_id = 0;
            
            $(document).ready(function() {
            
                $('#mybutt').click(function() {
                    item_id = $(this).attr('id').split('-')[1];
                    updateTimer();
                });

            
            }); //END $(document).ready()
            
            function updateTimer() {
                $.ajax({
                    type: 'POST',
                    url: 'getenddate.php`,
                    data: `item=` + item_id,
                    success: function(fromPhp) {
                        $('#countdown').html(fromPhp);
                        
                        //or, to change this item's end date as echoed out from $dynamicList:
                        //$('#ed-' + item_id).html(fromPHP);
                    } //END success fn
                }); //END AJAX code block
                adder = 0;
            } //END updateTimer fn

        </script>
    </head>
<body>

    <div id="countdown"></div>
    <input id="item-12" type="button" value="Add One Minute">


</body>
</html>

PHP: getenddate.php

<?php

    //item is NAME of var being posted over (key), 
    //item_id is the var contents on the client side ONLY
    //$_POST['item'] is var contents (value) as it arrives on PHP side
    $itemid = $_POST['item'];

    // ** FIXME the query contains a SQL injection vuln,
    // ** please untaint $itemid before using

    //code to return current time value from database - runs every time
    $end = mysql_result(mysql_query("SELECT `end_date` FROM item WHERE `id` = '$item' "), 0);
    
    echo $end;
    
halfer
  • 19,824
  • 17
  • 99
  • 186
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • okay, 2 hours later and I'm still stuck! I'm not going to bother you anymore mate and I appreciate your help. Nothing works and I tried your code and that didn't work either! gonna have to see if i can find another way of doing this. and by the way, the `` shouldn't be inside the Div tags. I just put it there to make sure I'm getting the data from the mysql as a test. – EnergyLynx EnergyLynx Sep 19 '13 at 18:32
  • Listen mon ami, AJAX *is* your answer. Not sure where you are having difficulty, but please experiment with the simple examples I posted earlier. Try the one with the two select boxes, just to see how AJAX works. Perhaps you'll get that epiphany. Sometimes it helps to close one question and create a greatly simplified example of what you want to do, then build up from there. Separate the timer part from the rest.... [Have a look at this SO post](http://stackoverflow.com/questions/17120478/how-to-update-the-php-current-timestamp-using-jquery-javascript-every-second) – cssyphus Sep 19 '13 at 19:14
  • Okay, Although I am not good at working with AJAX but I know how AJAX works. and i know that AJAX is my answer but I cannot understand the code you provided as it has so many different ID's, Names which don't exist in my own code or my mysql database. thats what confuses me! – EnergyLynx EnergyLynx Sep 19 '13 at 19:44
  • I know i said i wont bother you but is there any chance i could go in a chat with you please for a few so i can get the hang of your code and i might be able to get something done? – EnergyLynx EnergyLynx Sep 19 '13 at 19:46
  • Simplify. Let me remove the optional bits and repost (another answer -- I won't delete what I've written in case you want to go back and review the extra bits later). Give me a moment to create that. – cssyphus Sep 19 '13 at 19:47
  • I've added a SQL warning injection to the code here - some folks will copy+paste code and use as-is, so it pays to be explicit about any security issues. Feel free to adjust further. – halfer Nov 07 '21 at 10:27
0

If I understood you right, you want to change the content of a DIV, no matter what is inside. This can be accomplished like this:

in the HTML you have something like:

<div id="mydiv">My old content, no sites here</div>

An in the JS(jQuery enabled) you do (for example in the ready function):

$(document).ready(function () {
   $('#mydiv').html("This content is brand new");
});

jsFiddle of the code above

The .html() function deletes the old content of that tag and replaces it with new content.

If you, for example, want to show the current seconds, you can do as follows:

$(document).ready(function () {
    setInterval(function(){
      // change time
      $('#mydiv').html("Seconds: "+ new Date().getSeconds());
    },1000); 
});

jsFiddle of the code with counter

Daniel
  • 20,420
  • 10
  • 92
  • 149
  • @EnergyLynxEnergyLynx The code does work, see [this jsFiddle](http://jsfiddle.net/WtGJt/) – Daniel Sep 19 '13 at 15:21
  • @EnergyLynxEnergyLynx [Here](http://jsfiddle.net/WtGJt/1/) is the version with the counter – Daniel Sep 19 '13 at 15:22
  • This answer will only work for one user. The changes will not be seen by another user who visits the site. OP states that all users must see the same time. – cssyphus Sep 19 '13 at 16:15
  • @gibberish, All the other answers also only work for one user. basically they only work client side (not server side). – EnergyLynx EnergyLynx Sep 20 '13 at 08:52
  • @EnergyLynxEnergyLynx Not true. IF you store each item's end_date in the server db, and IF you use AJAX to update the end_date in the db (all clients updating same db), and IF you use AJAX to get the current time offset (end_date) and time from the server -- and then adjust it for each clients time zone -- THEN all users will see the same end_date/time for that item. – cssyphus Sep 20 '13 at 15:54
  • @EnergyLynxEnergyLynx Please recall my suggestion that you should store two bits of info re the `end_date`: (1) the end_date, and (2) an offset (INT 4 digit max) for added minutes for that specific item's end_date. Your AJAX code to get time from server (runs every second) sends the item_id with the request. On server side, it gets the end_date PLUS OFFSET for that item, performs the math to add the num extra minutes to the end_date, and returns the revised end_date. That way every client sees the same end_date. – cssyphus Sep 20 '13 at 15:57
  • @gibberish, if you remember from my code that I sent you yesterday, I am already storing the end_date in mysql database! I also, store the added time (1 minute) in the mysql database! and my current page shows the added time(1 minute) on page refresh! so everything is done nicely. so I dont need all the long winded maths etc. I just need to refresh the Div. seems quite simple aint it. but its not. – EnergyLynx EnergyLynx Sep 20 '13 at 17:43
  • @EnergyLynxEnergyLynx What is the name of the `added time` field? Do all users increment this field, or is it really just a `yes/no` or `0/1` field? What happens if two users are on page, viewing same item, and both hit the `Add 1 minute` link? Is the `added time` field in the DB incremented twice? That is, is the `added_time` now set to `1` or `2` ? – cssyphus Sep 20 '13 at 17:49
  • @gibberish, the name of the added time field is `time_added`. all the users increment this field. Yes. if two users are on the same page and they click on the button, two minutes will be added to the `time_added` field in mysql. just to be clear, my code (the one i sent you yesterday) does all this just fine. I thought you knew all this! – EnergyLynx EnergyLynx Sep 20 '13 at 18:06
0

This should be almost exactly what you are looking for (untested):

HTML:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

        <script type="text/javascript">
            var adder = 0; //Global var -- outside document.ready

            $(document).ready(function() {

                $('#mybutt').click(function() {
                    adder++;
                    updateTimer();
                });


            }); //END $(document).ready()

            function updateTimer() {
                $.ajax({
                    type: 'POST',
                    url: 'myphpprocessor.php',
                    data: 'addval=' + adder,
                    success: function(fromPhp) {
                        $('#theTimer').html(fromPhp);
                    } //END success fn
                }); //END AJAX code block
                adder = 0;
            } //END updateTimer fn

        </script>
    </head>
<body>

    <div id="theTimer"></div>
    <input id="mybutt" type="button" value="Add One Minute">


</body>
</html>

PHP: myphpprocessor.php

<?php

    $howmuch = $_POST['addval'];

    if ($howmuch > 0) {
        //code to update database by the amount
        //  - only runs if howmuch has a value
    }

    //code to return current time value from database - runs every time
    $thetime = mysql_query('SELECT etc etc etc');

    echo $thetime;

Notes:

  1. The database only needs to store the number of minutes to be added to the current time
  2. Your PHP code can then:
    (a) Query the DB for number of mins to add: $num_mins_to_add
    (b) Create a new date object with current time
    (c) Add the $num_mins_to_add to (b) (d) ECHO back the value
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • This is again using an external php page which i i don't want to use. there must be a way to do it on the same page. its only refreshing div crying out load. – EnergyLynx EnergyLynx Sep 19 '13 at 16:15
  • also, the code to return current time from mysql already is on another page. i'm trying to keep everything as minimal as possible and not having so many AJAX calls etc... – EnergyLynx EnergyLynx Sep 19 '13 at 16:18
  • I have EDITED my question again and updated it with my full code. as you can see I have everything ready and all i need is a way of refreshing the DIV. i hope this can be done without so many AJAX calls? – EnergyLynx EnergyLynx Sep 19 '13 at 16:30
  • also, why Can't it be done on the same page? why do i need to send data back and forth ? – EnergyLynx EnergyLynx Sep 19 '13 at 16:33
  • @EnergyLynxEnergyLynx The *only* way to update the div (after checking with a database) is to use AJAX. You can minimize the AJAX calls only by restricting the number of times your page checks with the database. – cssyphus Sep 19 '13 at 16:34
  • Even if you were doing it "on the same page", you would still be sending data back and forth... Think about it. The page is interpreted/viewed on the *client*, but... It is the *server* that checks the database, not the client. The database is on the *server*. Etc. ... Problem is, there's no other way to code this in order to: (1) update the div every second (2) after checking the database. – cssyphus Sep 19 '13 at 16:35
  • @EnergyLynxEnergyLynx, you can do it with a single page if you're happy to refresh the entire page when someone clicks the input, is that what you're looking for? If so I'll post a new answer explaining how. If not you have to use ajax. – andrew Sep 19 '13 at 16:36
  • @andrew, ofcourse i don't want to reload the entire page. that is easy and defeats the point of my question! – EnergyLynx EnergyLynx Sep 19 '13 at 16:38
  • 1
    @EnergyLynxEnergyLynx well then you need to get over the whole idea of not using an external page that's how http://api.jquery.com/jQuery.ajax/ works – andrew Sep 19 '13 at 16:40
  • @EnergyLynxEnergyLynx All you need to do is modify my second answer to do as commented. Rename the page `timechecker.php` (also in the AJAX code) and remove the bit about checking the `$howmuch` var -- in fact, you can remove the entire `data: addval=` line from the AJAX since there is no data to send to the server. Just check and return the end date, as shown. – cssyphus Sep 19 '13 at 16:40
  • @gibberish I'm sure he noticed but you have a backtick instead of a quote after the ajax url property – andrew Sep 19 '13 at 16:48
  • @andrew, yes, i noticed that and fixed it my code. Thanks for mentioning it. – EnergyLynx EnergyLynx Sep 19 '13 at 16:53
  • @andrew Thanks for catching that -- you have better eyes than I. – cssyphus Sep 19 '13 at 16:58