繁体   English   中英

如何使用Ajax将数据从Javascript传递到PHP

[英]How to pass data from Javascript to PHP using ajax

我正在努力从远程服务器接收JSON格式的数据并将其保存到数据库中。 远程服务器每隔一分钟更新一次数据。

我编写了一个JavaScript程序,该程序从远程服务器接收jason数据。 现在的问题是我无法将此数据传递到PHP文件以保存在数据库中。

我在stackoverflow上的同一线程上尝试了该解决方案,但到目前为止这些都行不通。

我正在尝试打印从php中的js接收的数据,以查找是否接收到数据。 我编写的代码可以运行,但是什么也没有发生。 按F12时无错误。

这是我的代码。 我在做什么错了。

编辑

我发现的另一个问题是它没有打印回显。 这意味着如果我尝试简单地回显“ test” ;,它不会打印任何内容。 我在下面添加完整的代码,以查看如何/在何处使用echo打印结果。 为什么回声不打印?

使用Javascript:

<script>

        var humArray = [];
        var temArray = [];
        var N = 24;
        for (i = 0; i < N; i++) {
            humArray.push(0);
            temArray.push(0);
        }

    function loadChart() { //fetches json data & calls dspChart() to render graph 
        var wData, hum, tem;
        var requestURL = 'https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s'; //URL of the JSON data
        var request = new XMLHttpRequest({
        mozSystem: true
        }); // create http request
        request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
        wData = JSON.parse(request.responseText);
        hum = wData.humidity;
        tem = wData.temperature;
        humArray.shift();
        humArray.push(hum);
        temArray.shift();
        temArray.push(tem);
        //dspChrt(humArray, temArray);

        $.ajax({
        url: 'index.php',
        type: 'GET',               
        data: { temArray : temArray, humArray : humArray },
        success: function (data) {
        console.log( data );
        },
        error: function (data) {
        console.log(data);
        },

         });            

        }
    }
        request.open('GET', requestURL);
        request.send(); // send the request
            //dspChrt(hum);
    }
      var myVar = setInterval(loadChart, 60000);  
    </script>            

的index.php

<?php

     if (isset($_GET['data']))
     {

      $WData = $_GET['data'];
      $Humidity = data.humArray;
      $Temprature = data.temArray;

      echo "Hum".$Humidity."Temp".$Temprature;

          } 
     ?>

完整代码

<div class="container">

    <div class="row">

            <div class="col-sm" style="background-color: #FFFFFF">

            <h2 style="color:#B93B8F;">Data from JS</h2>

        <?php

        $servername = "localhost";
        $username = "postgres";
        $password = "test123";
        $dbname = "testDB";

        class TableRows extends RecursiveIteratorIterator {
        function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
        }

            function current() {
                return "<td style='width:150px;border:1px solid grey;'>" . parent::current(). "</td>";
        }

            function beginChildren() {
                echo "<tr>";
        }   

            function endChildren() {
                echo "</tr>" . "\n";
        }
            }


                ?>

            </div>


        <?php

        if (isset($_GET['data']))
        {

        $WData = $_GET['data'];
        $Humidity = $WData.humArray;
        $Temprature = $WData.temArray;

        echo "Hum".$Humidity."Temp".$Temprature;

        } 

        ?>


        <h2>JS Update</h2>
          <div>
            <canvas id="myChart"></canvas>
         </div>


        <div class="col-sm" style="background-color: #FFFFFF">
                <?php
                    echo "<h3>WeatherData</h3>";
                    echo "<table class='table table-hover table-bordered table-reponsive'>";
                    echo "<thead class='table-dark'>";
                    echo "<tr><th>humidity</th><th>temprature</th></tr>";

                try {
                    $conn = new PDO("pgsql:host=$servername;dbname=$dbname", $username, $password);
                    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $stmt = $conn->prepare("SELECT humidity, temprature FROM weatherdata");
                    $stmt->execute();

                    // set the resulting array to associative
                        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
                            foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
                                    echo $v;
                            }
                        }
                    catch(PDOException $e) {
                    echo "Error: " . $e->getMessage();
                                        }       
                    echo "</thead'>";
                    echo "</table>";

                ?>

                <div id="form">

                    <div id="login">
                        <form action="" method="post">
                            <input type="text" name="humidity" id="humidity" required="required" placeholder="Enter humidity"/>
                            <input type="text" name="temprature" id="monikulmio_gps" required="required" placeholder="Enter temprature"/>
                            <input type="submit" value="Insert" name="submit12"/><br />
                        </form>
                        <hr/>
                    </div>

                    <?php

                    if(isset($_POST["submit12"])){

                    try {


                        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
                        $sql = "INSERT INTO weatherdata (humidity, temprature)
                        VALUES ('".$_POST["humidity"]."','".$_POST["temprature"]."')";
                        echo "<meta http-equiv='refresh' content='0'>";
                        if ($conn->query($sql)) {
                            echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
                        }
                        else{
                            echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
                        }

                        $dbh = null;
                    }
                    catch(PDOException $e)
                    {
                        echo $e->getMessage();
                    }

                }   

                $conn = null;

                ?>

                </div>

            </div>


        </div>
    </div>

    </div>

</body>

在您的PHP中,您正在检查isset $_GET['data']但它总是会失败。 您不发送数据,而是发送temArray和humArray。 所以在$_GET['humArray']$_GET['temArray']上使用isset

因此,您的代码将是:

<?php

   if (isset($_GET['humArray'])){
       $Humidity = $_GET['humArray'];
       $Temprature = $_GET['temArray'];
       echo "Hum".$Humidity."Temp".$Temprature;
   } 
?>

我还假设:

  1. 您的js将数据发送到php。
  2. 即使您说的是humArray和temArray,也只是在获取变量而不是数组。

如果这些是数组,则需要执行操作(而不是使用echo):

print_r($Humidity);
print_r($Temprature);

尝试将您的代码分成至少两个文件:

  1. index.php-带有html和javascript;
  2. fetchWeatherRequest.php-以下代码。

使用以下命令更新您的JavaScript代码:

$.when( $.ajax({
    type: 'POST',
    url: 'fetchWeatherRequest.php',
    dataType: 'json'
  })
).then( function( response ) { 
    // Code so render results on index.php;
});

fetchWeatherRequest.php:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  // Here code to save $response into database;

  echo $response;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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