0

I am using a PHP script to send JSON data to my website. I am using javascript to try and iterate through my json data so that I can store the information in an array.

The line var length = emails.length gives an error that email is an object

<script>
      var emails;
      $.get("scripts/getUsers.php", function(data) {
        for(element in data.email) {
          emails.push(element);
        };
      });
      var length = emails.length;
      alert(length);
      for(i = 0; i < length; i++) {
        $('<div/>', {
          'class':'col-md-3 col-xs-12 widget widget_tally_box',
          'html':'<p>Hello' + i + '</p>'
        }).appendTo("body");
      }
</script> 

Here is the PHP script

<?php

require_once '../includes/DBCredentials.php';

$response = array();

if($_SERVER['REQUEST_METHOD'] == 'GET') {
$db = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME);
$statement = $db->query("SELECT email FROM user");
while($row = $statement->fetch_assoc()) {
  $email = $row['email'];
  $response['email'] = $email;
}
echo json_encode($response);
}

?> 
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • use your browser dev console to see what "data", "data.email" and "emails" contain. – JimL Jul 07 '17 at 18:59
  • You need to move the loop into the callback from the get: `$.get("scripts/getUsers.php", function(data) { for(element in data.email) { emails.push(element); }; var length = emails.length; alert(length); }); ` – mplungjan Jul 07 '17 at 19:00
  • 1
    [$.get()](https://api.jquery.com/jquery.get/) is asynchronous, `emails` won't have the request data by the time the `alert()` and `for` loop are reached – Patrick Barr Jul 07 '17 at 19:01

0 Answers0