简体   繁体   中英

How to pass data from Javascript to PHP using ajax

I am working on to receive data in JSON format from a remote server and save it into database. The remote server updates the data each one minutes.

I have written a JavaScript program that receives the jason data from the remote server. Now the problem is I am not able to pass this data to PHP file to be saved in database.

I tried the solution from same threads on stackoverflow but those do not work so far.

I am trying to print the data received from the js in php to find if data is received. The code I have written runs, but nothing happens. It shows no error when pressing F12.

Here is my code. What is wrong I am doing in it.

EDIT

One more problem I figured out is it's not printing the echo. That mean if I try to simply echo "test";, it doesn't print anything. I add full code under to see how/where I am using echo to print the results. Why echo don't get print ?

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;

          } 
     ?>

FULL CODE

<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>

in your php you are checking if isset $_GET['data'] but it will always fail. You don't send data you send temArray and humArray. So use isset on $_GET['humArray'] or $_GET['temArray']

So your code will be:

<?php

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

I also assume that:

  1. your js is sending data to php.
  2. even if you say humArray and temArray you are fetching just variables and not arrays.

if these are arrays you need to do (instead of using echo):

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

Try to separate your code into at least two files:

  1. index.php - with html and javascript;
  2. fetchWeatherRequest.php - with code below.

Update your javascript code with:

$.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;
}

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