DawnZHANG DawnZHANG - 1 month ago 7
PHP Question

How to use AngularJS's several ajax call($http) to request data from a single php file?

I'm trying to use several AngularJS's ajax call to call a single php file to get different json data accordingly, below is my code:



var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $http) {
$http.get('myphp.php',{key: "main1"}).then(function (response){
console.log(response);
//do something
});
$http.get('myphp.php',{key: "main2"}).then(function (response){
//do something
});
});

<html ng-app="myApp">
<header>
<!-- AngularJS-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</header>
<body>
<div ng-controller="MyController">
<div id="main1">
</div>
<div id="main2">
</div>
</div>
</body>
</html>





In myphp.php file I have:



<?php
if (isset($_GET["key"])) {
if ($_GET["key"]=="main1") {
$url1 = 'http://www.w3schools.com/angular/customers.php';
$content = file_get_contents($url1);
echo $content;
}
else if ($_GET["key"]=="main2") {
$url2 = "blabla"
$content2 = file_get_contents($url2);
echo $content2;
}
}
?>





As you can see, I'm trying to differentiated different ajax calls and try to get correct data from the counterpart ajax call from php by sending a value while calling myphp.php.

The problem is,,,,it won't work, I'm guessing that my syntax is messed up, can you guys help? Thank you so much in advance!

This is the result I got:
enter image description here

I add "var_dump($_GET);" at the top of my php code and this is what I got.
enter image description here

Answer

You have some errors in html and angular logic.

In html you declare your ng-app directive before load angular core

 <html >
<header>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
</header>
<body ng-app="myApp">
    <div ng-controller="MyController">
      <button ng-click="getContent('main1')"> main1</button>
      <button ng-click="getContent('main2')"> main2</button>
      <pre>{{content | json}}</pre>
    </div>
</body>
</html>

we already saw the logic errors in php :)

<?php
if (isset($_GET["key"])) {
    if ($_GET["key"]=="main1")
        $url = 'http://www.w3schools.com/angular/customers.php';
    else if ($_GET["key"]=="main2")  
        $url = "https://www.google.com";

    $content = file_get_contents($url);
        echo $content;
}
?>

in angular you call twice the $httpservice without correct parameters.

var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $http) {


    $scope.getContent = function(key){
        console.log("dsa")
        $http.get('myphp.php',{params: {key: key}}).then(function (response){
        console.log(response);
        $scope.content = response.data;
    });
    }
 });