I want to retrieve users info by a function in PHP
in my angular.
angular code:
$scope.users = $http({
method: 'GET',
url: 'functions.php/getUsers()'
}).then(function(response){
$scope.users = response.data;
},function(reason){
$scope.error = reason.data;
});
}
where getUsers()
is the function which is returning json
data to the angular.
is there any other way to use functions in angular from a PHP
files?
remember the
functions
can not be equal to our public variable, in this sample you have$scope.users
asfunction
and also you have that again equal toresponse.data
(actually you miss thefunction
)you can't read from files, you have to use api URL which return
json
to you
$scope.users = $http({
method: 'GET',
url: 'functions.php/getUsers()'
}).then(function(response){
$scope.users = response.data;
},function(reason){
$scope.error = reason.data;
});
}
change to
$scope.getUsers = function(){
//for example api url for your users is "http://localhost:8080/users"
var api = "you api url";
$http({method: 'GET', url: api}).then(function(response){
$scope.users = response.data;
},function(reason){
$scope.error = reason.data;
});
}
}
//request data
$scope.getUsers();
OR use it directly without function
//for example api url for your users is "http://localhost:8080/users"
var api = "you api url";
$http({method: 'GET', url: api}).then(function(response){
$scope.users = response.data;
},function(reason){
$scope.error = reason.data;
});
}
You can not call a PHP function in a JavaScript file in this way. You can do it by following these steps:
1) create get-users.php
file
<?php
require 'functions.php';
echo getUsers();
?>
2) make the http request to the created file
$scope.users = $http({
method: 'GET',
url: 'your-website-url/get-users.php'
}).then(function(response){
$scope.users = response.data;
},function(reason){
$scope.error = reason.data;
});
}
Update
if you have a lot of functions and don't want to create a file for every function. then you can do it like this:
1) create all-functions.php
file
<?php
require 'functions.php';
if (function_exists($_GET['func'])) {
echo call_user_func($_GET['func']);
} else {
echo "Error: function does not exist";
}
?>
2) Update your angular code
$scope.users = $http({
method: 'GET',
url: 'your-website-url/all-functions.php',
data: {
func: 'getusers'
}
}).then(function(response){
$scope.users = response.data;
},function(reason){
$scope.error = reason.data;
});
}