Jquery JSON parse returns undefined

Hello everyone.
I’m trying to create a long polling with php , jquery and ajax.
The file “server.php” encodes a json of the last row inserted in mysql.
If i run it directly it shows up correctly, for example:

["87","2017-11-20","2017-11-20 09:43:02","lunedi 9.42","","5"]

when I run the “results” file , it keeps looping and it say “undefined”.

here the CLIENT.JS

function getContent( timestamp )
{
    var queryString = { 'timestamp' : timestamp };
    $.get ( 'http://127.0.0.1/server/server.php' , queryString , function ( data )
    {
        var obj = jQuery.parseJSON( data );
 
        for (var k in obj)
        {
            var comment = "<p>" + obj[k].comment + "</p>";
            var timestamp = obj[k].timestamp;
            $( '#response' ).append( comment );
        }
 
        // reconecta ao receber uma resposta do servidor
        getContent( timestamp );
    });
}
 
$( document ).ready( function ()
{
    getContent();
});

and here RESULTS.HTML

<html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="client/client.js"></script>
    </head>
    <body>
        <h1>ORDINI</h1>
        <div id="response"></div>
    

    </body>
</html>

is there anyone who can help me?

The problems are twofold.

(1) - your request returns an array of strings, not of objects.

(2) - a for..in loop is intended for objects, not for arrays (for which you have the forEach() method)

Sorry, I responded in the other topic for this. My comment there seems to be correct while the OP is only retrieving a single row from the server each time, but if they receive more than one it will need to loop twice.

var obj = jQuery.parseJSON(data);
  for (var k in obj) 
    {
	for (var l in obj[k]) {
	  alert(l + " " + obj[k][l]);
	  }
	 }

I’m sure there are more elegant ways of doing this.

Thank you droopsnoot, when I realized that the problem was in Jquery , I opened a new thread in Javascript forum.
I tried your code, but nothing happens.
What I need to do is to open a long polling to the server, and, if there is a new row in the table , I need to display it in a div, formatting in as I need

Now I’m able to display the data with:

function getContent( timestamp )
{
    var queryString = { 'timestamp' : timestamp };
    $.get ( 'http://127.0.0.1/server/server.php' , queryString , function ( data )
    {
        var obj = jQuery.parseJSON( data );
 
        
            $(" #response ").append(obj);
 
        // reconecta ao receber uma resposta do servidor
        getContent( timestamp );
    });
}
 
$( document ).ready( function ()
{
    getContent();
});

but now RESULTS.HTML keeps displaying the last entry indefinitely , instead of printing once and then to wait for another entry

I took the snippet from here:

but probably I’m not able to adapt it to my need,

that is what it is essentially instructed to do, since any call to getContent() calls itself with the same parameters, and hence receives the same result, forming an infinite loop.

You are right.
I’m not sure how to modify it in order to print content only once and to keep searching for new entries.

that must be done on the server side. alternately pass an explicit timestamp instead of undefined.

Does the table have an auto-incrementing id column? If it does, you could use that instead of the timestamp. Return it as part of the data, and request the next record with an id greater than the last one you displayed.

It could be a good solution.
I’m not so good in coding,so for the moment I decided for a simpler way.
I refresh a div every 2 second:

RESULTS.PHP

    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <link rel="stylesheet" href="orders_style.css">
        <script  > 
        function ajaxCall() {
                                $.ajax({
                                url: "ajax.php", 
                                success: (function (result) {
                                    $("#response").html(result);
                    })
                    })
                    };

            ajaxCall(); // To output when the page loads
            setInterval(ajaxCall, (2 * 1000)); // x * 1000 to get it in seconds
</script>
       
    </head>
    <body>

        <h1>ORDINI</h1>
        <div id='response'></div>
        
    

    </body>
</html>

AJAX.PHP

<?php
include "connect.php";
// Other variables needed to perform the query, such as $message_query
// needs to be here as well
if (!$result = $cn->query("SELECT timestamp,nameclient,emailclient  FROM shoppingcart ORDER BY timestamp DESC" )) {
    echo "Errore della query: " . $cn->error . ".";
    exit();
  }else{
if($result->num_rows > 0) {
      // conteggio dei record restituiti dalla query
      while($row = $result->fetch_array(MYSQLI_BOTH))
      { ?><table>
                <tr><td><?php echo "DATA:   " .$row['timestamp']?></td>
                    
                    <td><?php echo "CLIENTE:    ". $row['nameclient']?></td>
                    <td><?php echo "EMAIL:  " . $row['emailclient']?></td>
                    </tr></table><?php
              }
            
              // liberazione delle risorse occupate dal risultato
              $result->close();
            
          }         
 $cn->close();
        };
       


    ?>

    </body>
</html>

Thank you for your help!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.