简体   繁体   中英

Combine requests for multiple PHP files to one request

I have a dynamic web dashboard which displays data like temp, humidity, light, noise etc. I have multiple php files like temp.php, humidity.php, light.php and noise.php which take care of retrieving the data from db and then I have multiple js files too which basically use setTimeout and displays data from the corresponding php file to the html page every 3 seconds.

Each of the php file looks like this, example- humidity.php:

    <?php
    session_start();
    if(isset($_SESSION["user_id"])){
    include('db.php');
    $unit = "820";
    $stmt = $db->prepare("SELECT hv FROM humidity where 
unitid=? order BY pk DESC LIMIT 1");
    $stmt->execute([$unit]);
    $humidity= $stmt->fetchColumn();
    $humidity=round($humidity, 2, PHP_ROUND_HALF_ODD);
    echo $humidity;
    $stmt->closeCursor();
    $db = null;
    }
    ?> 

And each js file looks like this, example- humidity.js:

$(document).ready(function() {
        function foo() {
            $('#showhumidity').load('humidity.php');

            setTimeout(foo, 3000);
        }

    foo();


    });

The process is working fine, but since there are multiple php requests, the overall processing time is little high (around 2 seconds). I would like to combine the phps into one php file and the js files into one too - thereby having just one php request to retrieve all the data.

What is the best way to do it?

Hope below approach will help you.

In your combined php file:

<?php
  $humidity  = getHumidity(<parameter>);
  $temp = getTemp(<parameter>);
  $light = getLight(<parameter>);
  $retArr = array("humidity" => $humidity,"light" => $light, "temp" => $temp);
  echo json_encode($retArr);

  function getHumidity($param) { 
   // write your logic here to calculate the humidity
  }

  function getTemp($param) { 
   // write your logic here to calculate the temp
  }

  function getLight($param) { 
   // write your logic here to calculate the Light
  }

?>

In your single .js file:

jQuery(document).ready(function() {
    function foo() {
        jQuery.ajax({
            url : <path of your php file>,
            type : <Method GET/POST as per your requirement >,
            dataType : json,               
            async : false,
            success : function(data, status) {
               //update your html element with data
            },
    }

setInterval(foo, 3000);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM