Search code examples
javascriptphpangularjsphpstorm

AngularJS - PHP doesn't return values


I've recently decided to learn AngularJS and I'm currently trying to make a simple website with PhpStorm. I have stumbled upon a problem I don't seem to be able to solve.

This is the code of the website so far.

view.html

<button ng-click="doClick()">Click</button>

<table>
    <tr>
        <th>ID</th>
        <th>Condition</th>
    </tr>
    <tr ng-repeat="x in items track by $index">
        <td>{{ x.id }}</td>
        <td>{{ x.condition }}</td>
    </tr>
</table>

view.js

'use strict';

angular.module('myApp.view', ['ngRoute'])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/view', {
            templateUrl: 'view/view.html',
            controller: 'ViewCtrl'
        });
    }])

    .controller('ViewCtrl', ['$scope', '$http',
        function($scope, $http) {
            $scope.doClick = function() {
                $http({
                    method: 'GET',
                    url: 'view/view.php'
                }).then(function(response) {
                    $scope.items = response.data;
                })
            };
        }
    ]);

view.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

$connect = mysqli_connect($servername, $username, $password, $dbname);

if(!$connect) {
    die("Connection failed: " . mysqli_connect_error());
}

$query = "SELECT * FROM table";
$result = mysqli_query($connect, $query);

if(mysqli_num_rows($result) > 0) {
    $output = array();

    while($row = mysqli_fetch_assoc($result)) {
        $output[] = $row;
    }

    echo json_encode($output);
}

else {
    echo "No Results";
}
?>

I would like to get the values from my variable $output. However, once I run the PHP code it only returns the whole code. It doesn't seem to recognise my PHP file as code in PhpStorm but runs just fine when accessing it through "localhost/view.php".

I've tried solutions from similar threads but with no luck so far. I'm using Apache and MySQL, if that is somehow important. Any help would be appreciate!


Solution

  • Once I changed the URL inside my function from

    url: 'view/view.php'
    

    to

    url: 'localhost/view.php'
    

    the PHP file worked as intended. As a side note, the PHP file was inside my project folder at first and I moved it to my Apache deployment folder to make it work. I hope this answer is understandable. Thank you @Ayaou for helping me out here!