Lizardan
Lizardan

Reputation: 1

PHP not Sending JSON Object to JavaScript

<?php
    header("Content-Type: application/json");
    if(isset($_POST['limit'])){
        $limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
        require_once("connect_db.php");
        $i = 0;
        $jsonData = '{';
        $sqlString = "SELECT * FROM tablename ORDER BY RAND() LIMIT $limit";
        $query = mysqli_query($con, $sqlString) or die (mysqli_error()); 
        while ($row = mysqli_fetch_array($query)) {
            $i++;
            $id = $row["id"]; 
            $title = $row["title"];
            $cd  = $row["creationdate"];
            $cd = strftime("%B %d, %Y", strtotime($cd));
            $jsonData .= '"article'.$i.'":{ "id":"'.$id.'","title":"'.$title.'", "cd":"'.$cd.'"  },';
        }
        $now = getdate();
        $timestamp = $now[0];
        $jsonData .= '"arbitrary":{"itemcount":'.$i.', "returntime":"'.$timestamp.'"}';
        $jsonData .= '}';
        echo $jsonData;
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            var myTimer;
            function ajax_json_data(){
            var databox = document.getElementById("databox");
            var arbitrarybox = document.getElementById("arbitrarybox");
            var hr = new XMLHttpRequest();
            hr.open("POST", "json_mysql_data.php", true);
            hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                    var d = JSON.parse(hr.responseText);
                    arbitrarybox.innerHTML = d.arbitrary.returntime;
                    databox.innerHTML = "";
                    for(var o in d){
                        if(d[o].title){
                            databox.innerHTML += '<p><a href="page.php?id='+d[o].id+'">'+d[o].title+'</a><br>';
                            databox.innerHTML += ''+d[o].cd+'</p>';
                            }
                        }
                    }
                }
                hr.send("limit=4");
                databox.innerHTML = "requesting...";
                myTimer = setTimeout('ajax_json_data()',6000);
            }
        </script>
    </head>
    <body>
        <h2>Timed JSON Data Request Random Items Script</h2>
        <div id="databox"></div>
        <div id="arbitrarybox"></div>
        <script type="text/javascript">ajax_json_data();</script>
    </body>
</html>

PHP code goes on a separate file called "json_mysql_data.php". I'm just following this tutorial from https://www.youtube.com/watch?v=-Bv8P5oQnFw and it runs fine for him but not for me. I tested "connect_db.php" with mysql alone and it works fine. It seems to me like php doesn't go pass if (isset ($_POST['limit'])) but why...On the html file I get the "requesting..." message from the javascript code which means is waiting for PHP. Thanks for your help guys.

Upvotes: 0

Views: 128

Answers (2)

Lizardan
Lizardan

Reputation: 1

Thank you for your help @arielnmz. I found the problem. PHP was having issues with the getDate() function because the date.timezone field was not configured in the PHP.ini file. Adding the following line to the file fixed the problem:

date.timezone = "UTC"

Upvotes: 0

arielnmz
arielnmz

Reputation: 9115

You check for the ready state and change the content of databox with the response JSON inside the onreadystatechange function:

hr.onreadystatechange = function(aEvt) {
    if(hr.readyState == 4 && hr.status == 200) {
        …
        databox.innerHTML += …;
        …
    }
    …
    databox.innerHTML = "requesting...";
    …
}

But you change the HTML of the databox:

databox.innerHTML = "requesting...";

Still inside the block of the onreadystatechange function and after you receive the response, so the databox will always say "requesting..." no matter what you receive. You have to move the part that prints "requesting..." outside of it:

hr.onreadystatechange = function(aEvt) {
    if(hr.readyState == 4 && hr.status == 200) {
        …
        databox.innerHTML += …;
        …
    }
    …
}
…
databox.innerHTML = "requesting...";
…

Update:

Also, it seems that your function ins't defined correctly, as you can see, the one on the MDN reference pages example receives a parameter:

req.onreadystatechange = function(aEvt) {
    …
}

But yours doesn't have such parameter:

hr.onreadystatechange = function() {
    …
}

Ans that's it.

Upvotes: 1

Related Questions