0

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>

16
  • In your index.PHP, you are trying to access data.humArray, this should be $WData.humArray, and the same for temArray. Commented Aug 23, 2018 at 9:40
  • Here you got a mistake : data: { temArray : temArray, humArray : humArray } try this : data: { "temArray" : temArray, "humArray" : humArray } Commented Aug 23, 2018 at 9:40
  • 1
    Why on earth are you using xmlhttprequest and in there $.ajax??? Commented Aug 23, 2018 at 9:43
  • 2
    Why are you doing this via client-side JS in the first place, when you eventually want to store the data on your server? Commented Aug 23, 2018 at 9:54
  • 1
    Use curl on the server - then no need for CORS.io at all Commented Aug 23, 2018 at 10:07

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

It's array as you see at declaration 'var humArray = [];'. I tried both ways i.e. (isset($_GET['humArray'])) & print_r($Humidity);. But don't work. Now figure an error that I put in OP missing }. That's probably causing no output. Trying to figure it out.
error gone, it was a missing comma after data assignment curly brace but it's still printing none with both ur edits.
I search more liking threads on stackoverflow and some places, they use '$_GET['data']' like format while some places use $_GET['humArray']. Its confusing.
0

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

2 Comments

Thank you very much for the help. I will consider implementing this way too since start of stuff. Will need to study / get info which approach is more appropriate. I think @Cbroe also show reservations on my approach. When I make working current code, then use this.
I think I will stick with this way i.e. how it should be. Unfortunately I started on wrong foot. Thank you very much for posting the code. It's easy in PHP to do using curl. Though I will have to fetch specific data types. I work more on it but probably will need more assistance. I think I accept yuor answer and open a new thread for any problems I face implementing curl.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.