hello
hello

Reputation: 33

Php JavaScript Refreshing Certain Divs

I want to do the following:

<html>
    <div id="first"><?php echo time(); ?></div>
    <div id="second">My dropdown menu goes here</div>
    <div id="third"><?php echo time(); ?></div>
</html>

I have this "example.php" and what I want is that refreshing first and third divs and PHP codes inside them every 1 second without reloading page and changing the state of the second div which will hold a selection from dropdown menu.

So the selection of the dropdown menu should be exact and when I click and open the dropdown menu, the menu must not be closed when a refresh occurs at first and third div.

Also, refresh method of the first and third div must be simultaneous and completely separate processes. Time printing is just for feeding a time changing value to my problem. I will read and print MySQL database data inside these PHP codes.

How can I do that using javascript? Thanks...

Upvotes: 1

Views: 70

Answers (2)

Jaswinder
Jaswinder

Reputation: 359

To achieve your desired result, You need to utilize Ajax and JSON.
Your PHP script will return fresh data as json which will be fetched via Ajax and then replaced in the target divs.

But before we begin let's learn a bit about Ajax and JSON

What is Ajax?

Ajax is a client-side script that communicates to and from a server/database without the need for a post back or a complete page refresh. Essentially, Ajax is “the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”

What is JSON?

JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.


How to integrate it with your script?
We will first define a javascript function named update_data() which fetches the values from the server and then updates the divs with their fetched values.

To do all this, we'll use jQuery as a dependency and will utilize it's jQuery.ajax() method
NOTE - To automatically call the function every second we will also need setInterval method

function update_data() {
   $.ajax({
       url: 'test.php',  // Your PHP script location
       type: "GET",
       async: true, // refer to reference [1] in my answer
       success: function (data) {
           // Update the values

           $('#first').text(data.time1); // get the value of `time1` key from returned data
           // #first targets the element with id="first"

           $('#third').text(data.time2);
        }
   });
}

setInterval("update_data();", 1000);
// calls the function `update_data()` every second

Sample PHP script- (test.php)

<?php
    if ($_SERVER['REQUEST_METHOD'] == "GET") {
        $data = Array('time1' => time(), 'time2' => time());

        // returns the data with mime type `json` instead of `html`
        header("Content-Type: application/json; charset=UTF-8");
        echo json_encode($data);  // converts array into json
    }
?>

The above PHP script will return the follwoing JSON structure:

{
    "time1": 'value returned by first call to time()',
    "time2": 'value returned by repeated call to time()'
}


Full html example (calls external php)-

<html>
    <div id="first">Print some value on page load, will be replaced by Ajax</div>
    <div id="second">My dropdown menu goes here</div>
    <div id="third">Print some value on page load, will be replaced by Ajax</div>
    <!-- Include jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        function update_data() {
            $.ajax({
                url: '/test.php', // Your PHP script location
                type: "GET",
                async: true, // refer to reference [1] in my answer
                success: function(data) {
                    // Update the values

                    $('#first').text(data.time1); // get the value of `time1` key from returned data
                    // #first targets the element with id="first"

                    $('#third').text(data.time2);
                }
            });
        }

        setInterval("update_data();", 1000);
        // calls the function `update_data()` every second
    </script>
</html>


Reference -
1. What does "async: false" do in jQuery.ajax()?

Upvotes: 1

Pedro Serpa
Pedro Serpa

Reputation: 161

Use http://api.jquery.com/jquery.ajax/

Example:

<script>
$(function(){
  $.ajax({
  url: "first.php",
  })
  .done(function( data ) {
    if ( data ) {
      $('#first').html(data);
    }
  });
});
</script>

Now, if you are really swimming off the pond, I'll make it easier:

    <script>
var t=0;
function fetchFirst()
{
     $.ajax({
      url: "first.php",
      })
      .done(function( data ) {
        if ( data ) {
          $('#first').html(data);
         clearTimeout(t);
        }
      });
}
    $(function(){
      t=setTimeout(fetchFirst, 1000)
    });
    </script>

Now you can get the rest from this quick start. Remember to embed jquery before this stuff with

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

and do not make too many requests simultaneously. Good luck.

Upvotes: 0

Related Questions