简体   繁体   中英

Fetch data from database in JSON using AngularJS and display it to the textbox

I am new to AngularJS. I just want to fetch data from my database and store it on the textbox.

Here's my code:

$scope.sample = function(){
    $http.post('query?action=get',{

    })
    .then(function(response){
        $scope.info = response;
    })
    .catch(function(response){
        alert("error");
     });
};
 // call the function
 $scope.sample();

and in PHP:

$action = $_GET['action'];

if($action == 'get'){

   $sql = "SELECT * FROM tableSomething";
   $sql_res = $con->query($sql);
   $data = array();
   while($row = mysqli_fetch_array($sql_res)){
         $data[] = $row;
   }

    echo json_encode($data);
}

and in my HTML File

<input type="text" ng-model="info.firstname" >

Tell me where I got mistake. Thanks!

Your response is an object.

First of all your server request is a GET and not a POST.

So change $http.post('query?action=get',{ with $http.get('query?action=get',{

If there are no other code issues you get data of response .

Replace $scope.info = response; with $scope.info = response.data;

Your example code lacks the definition of $scope , so I can not test it fully.

I hope I have solved your problem


UPDATE 1:

Ok. AngularJS is too much insightful.

It sees that the response content has a JSON structure and returns it as an object.

Let stringify:

.then(function(response){
        $scope.info = JSON.stringify(response);
    })

and change your

<input type="text" ng-model="info.firstname" >

to

<input type="text" ng-model="info" >

Here a JSFiddle Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM