user2168066
user2168066

Reputation: 635

Error printing Ajax data to html table

I have a php function to generate a list of numbers, and an ajax call to retrieve that array of numbers. I can alert the list and it works fine, however when I try to print it into an HTML table I get the error "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in Infinity" Any help would be appreciated.

<!DOCTYPE html>
<html>
<head>
<script     src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$.ajax({
type: "POST",
url: "primeNumbers.php",
datatype: 'JSON',
success: function(data){
    var d = $.each(JSON.parse(data));
    var output;
    $.each(d,function(i,e){
        output += '<tr><td>'+e.data+'</tr></td>';
        });

    $('#table').append(output);

    alert(data);
}
});
</script>
<h1>Heading</h1>
<table id="table">
  <tr>
    <td>Name</td>
  </tr>
</table>

</body>
</html>

primeNumbers.php

<?php
function prima($n){

  for($i=1;$i<=$n;$i++){

          $counter = 0; 
          for($j=1;$j<=$i;$j++){ 


                if($i % $j==0){ 

                      $counter++;
                }
          }


        if($counter==2){

               echo json_encode($i);
        }

    }
} 
prima(100);  

?>

Upvotes: 0

Views: 236

Answers (1)

Yolo
Yolo

Reputation: 1579

The actual error means that $.each is probably getting the wrong data type. E.g. a string when in should be passed an object it can iterate over. In your case, both the javascript and the PHP code have some errors. Your PHP code just echoed the prime number. So you ajax function got back a concatenated string of numbers (the reason for your Uncaught TypeError). You have to push the numbers to an array, convert that to a json string and return that result, so you can echo it anywhere you need it.

Regarding only your ajax function. Loose $.each() in your variable declaration. So:

var d = $.each(JSON.parse(data));

becomes:

var d = JSON.parse(data);

UPDATE added PHP fix

Here is the fixed/refactored PHP function.

function prima($n){

   $res = []; // Initiate result array

   for($i=1;$i<=$n;$i++){

      $counter = 0; 
      for($j=1;$j<=$i;$j++){ 


            if($i % $j==0){ 

                  $counter++;
            }
      }


    if($counter==2){
         $res[] = $i; // store value to array
    }

  }

  return json_encode($res); // return converted json object

}

header('Content-Type: application/json'); // tell browser what to expect
echo prima(100); // echo the json string returned from function

Upvotes: 1

Related Questions