-2

using angularjs to get data from sql via php delivered in json. when i hit the php page directly, i see the json results beautifully, but with my angular http call, all i get is an empty array.

sql.php:

header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("localhost", "****", "****", "****");
if(!$conn){
    die("Connection failed: " .mysqli_connect_error());
}

if($_GET['q'] == 'classes') {
    $query = "SELECT * FROM `assignments`";
}

if($_GET['q'] == 'allContacts') {
    $query = "SELECT * FROM `contacts`";
}

$data = array();
$result = mysqli_query($conn, $query);

if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        $data[] = $row;
    }
} else {
    echo "0 results";
}

$json = json_encode($data);
echo $json;

angular js:

$scope.classes = []
$http.get("sql.php?q=classes")
.then(function(res) {
  $scope.classes = res
}, function(err) {
  console.log(err)
})

console.log($scope.classes)
Phil
  • 157,677
  • 23
  • 242
  • 245
ken yoder
  • 31
  • 2
  • 5
  • `echo "0 results";` <- that's going to be a real problem for anything expecting a JSON response – Phil Apr 12 '18 at 01:54
  • Also, you probably want `$scope.classes = res.data`. See https://docs.angularjs.org/api/ng/service/$http#$http-returns – Phil Apr 12 '18 at 01:58

1 Answers1

0

here is what happening here, $http.get in angular is asynchronous(search for the meaning), so when you call it, it will not wait for the response instead it will move forward to the next instructions which is on your code is the console.log, so what happened here is when you call console.log which is also calling your $scope.classes it hasn't receives the response yet. to see it more further try to add timeout to your console.log but that's not the right way to do it, you need to understand about asynchronous call in javascript

cute_programmer
  • 332
  • 3
  • 13
  • i thought the ".then(function(res) {" was the asynchronous part. i'm still learning. how does one make what i have here work asynchronously? – ken yoder Apr 13 '18 at 02:08
  • the then function executed after the response is receive its a callback, its like saying "give me data from this person and THEN pass it to the user" if the data is retrieve the THEN will be executed and pass data to the user. i can't give you any solutions because you don't have even a problem. you are just logging the $scope.classes variable. if you want to really see if the var classes receives data, you can put your logging inside then or add timeouts. so as i said the solution depends if how you will use the data – cute_programmer Apr 13 '18 at 06:56