JoelContreras
JoelContreras

Reputation: 83

Refresh only a div from the same page, no external source

Im trying to refresh a div tag with jquery but it is not working.. i need to refresh a div so the php code gets executed and a text updated..

first i load jquery then the file that contains function i need to execute, and then refresh script, all on header:

  <script src="jquery-3.1.1.min.js"></script>

  <?php
     require "codes.php";
  ?>

  <script type="text/javascript">
      setInterval(function(){
         $('#ip').load('#ip');
      }, 1000);
  </script>

finally the div i want refreshed:

<div id="ip" class="navbar-header">
     <p style="text-align: center; color:white;">
         Your IP address is 
         <span style="color:red;">
            <?php
                echo getip();
            ?>
         </span>
     </p>

Upvotes: 0

Views: 984

Answers (1)

Taufik Nur Rahmanda
Taufik Nur Rahmanda

Reputation: 1969

The problem is your php echo will run once when page is opened. As the name of PHP which is abbr of (Hypertext Preprocessor ... bla bla bla) forgot ... so your php code will finally turn into just static html content on your page. Your js setInterval() and jQuery .load() is actually running but the $('#ip') content is still the same.

To be able to get data dynamicaly, you (must) need an external php file which will process the request of echo getip(); again and again.

So like this:

loadip.php

echo getip();

JS

$(document).ready(function() {
    setInterval(loadip,1000);
});

function loadip() {
    $("#ip").load("loadip.php");
}

Or ...

$(document).ready(function() {
    setInterval(function() {
        $("#ip").load("loadip.php");
    },1000);
});

Hope this help. Good luck!

Upvotes: 1

Related Questions