0


I have a PHP server page returning data in JSON format like this:

<?php 
$data = array(
    (object)array(
        'title' => 'myfirstvalue',
        'value' => 'myfirsttext',
    ),
    (object)array(
        'title' => 'mysecondvalue',
        'value' => 'mysecondtext',
    ),
);

$json = json_encode($data);
echo $json; 
?> 

Now I'd need to display the JSON title attribute using AngularJS. Taken from a tutorial I've adapted the following code:

<!DOCTYPE html>
<html lang="en">


<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>

<body ng-app="myapp">

  <div ng-controller="MyController" >
    <button ng-click="myData.doClick(item, $event)">Send AJAX Request</button>
    <br/>
    Data from server: {{myData.fromServer}}
  </div>

  <script>
    angular.module("myapp", [])
        .controller("MyController", function($scope, $http) {
            $scope.myData = {};
            $scope.myData.doClick = function(item, event) {

                var responsePromise = $http.get("http://localhost/myfunction.php");

                responsePromise.success(function(data, status, headers, config) {
                    $scope.myData.fromServer = data.title;
                });
                responsePromise.error(function(data, status, headers, config) {
                    alert("AJAX failed!");
                });
            }


        } );
  </script>

</body>

</html>

However nothing is displayed when I click on the button. Any idea where is the problem with this code ? Thanks!

1
  • 1
    if you put console.log(data) in success callback, does it show that data was received? Commented Mar 30, 2014 at 17:23

1 Answer 1

1

Line

$scope.myData.fromServer = data.title;

isn't good. In general 'yes' but not in these piece of code. Why? You PHP code return:

array(
    [0] => array(
        'title' => ...,
        'value' => ....
    ),
    [1] => array(
        'title' => ...,
        'value' => ....
    )
);

You don't have key 'title' there. You should use data[0].title to display results (key '0').

I preferring to use in these case UnderscoreJS (underscorejs.org). Method _.pluck(list, propertyName) seems for me to be good. Read more here - http://underscorejs.org/#pluck

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.