0

hope you fine and well ,

i want to ask if it possible to fetch data using $http.get from the same page , to go deep in details :

i have a php file called (MY_FILE.php) that contains : PHP,HTML and SCRIPT codes , in the PHP section i executed sql select statment, and im trying to fetch the selected data in the script to use it in the html part , is this possible ?!

php part :

<?php
$connect = mysqli_connect("localhost", "root", "", "database");
$result = mysqli_query($connect, "select * from table");
$data = array();
while ($row = mysqli_fetch_array($result)) {
    $data[] = $row;
}
print json_encode($data);

?>

script part :

fetch.controller('dbCtrl', ['$scope', '$http', function ($scope, $http) {
        $http.get("MY_FILE.php")
            .success(function(data){
                $scope.data = data;
            })
            .error(function() {
                $scope.data = "error in fetching data";
            });
    }]);

when i use any of the selected data in the html section nothing appear and stay blank.

any idea ?!

6
  • declare $scope.data = {}; in controller before $http.get Commented Mar 6, 2016 at 14:57
  • thank you but nothing changed . Commented Mar 6, 2016 at 15:07
  • Can you log out the data you get back from the request to confirm that you actually get something back? Log out $scope.data after you've set it. Commented Mar 6, 2016 at 15:14
  • Use promises docs.angularjs.org/api/ng/service/$http . You need to use .then() instead of .success() Commented Mar 6, 2016 at 15:15
  • Won't work if that file outputs anything other than the json for the $http request Commented Mar 6, 2016 at 15:20

1 Answer 1

1

The code is right, but the issue with using $http.get for the same page is when you use print json_encode($data); for returning response to the $http call, rather then returning call to $http, it prints the data on the page. So it returns nothng. So its better to use another page and using another page will be more user friendly as well because the page won't refresh for fetching the results. Secondly, because of the asynchronous nature of $http, the program will keep on executing and it won't be waiting for the php code to run and showing result. As soon as the php code is completely executed it will show the result.

And if you want everything to happen on same page you can simply use

<?php
    if(isset($_POST['varname']))
    {}
    ?> and
    <html>
    <form action="" method="POST" > 

    </form></html>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.