0

My index.html is :

<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
  <meta charset="utf-8">

  <title>HTTP Request</title>

  <script src="angularjs"></script>
  <script src="appjs"></script>

</head>
<body>

    <div ng-controller="myCtrl">

        Test here : <input ng-model="testString">
        <p>Test String is : {{testString}}</p>
        <button ng-click="search()">Send HTTP Request</button>
        <p>Response:</p>
        {{data}}
    </div>

</body>
</html>

And my app.js is :

angular.module('myApp', [])
    .controller('myCtrl', ['$scope', '$http', function($scope, $http) {
        $scope.testString = "Hello....";

        $scope.search = function() {
//          alert("inside search");
            $http.get('www.google.com', {},
                function(response) {
                    $scope.data = response;
                    alert("success");
                },
                function(failure) {
                    alert("failure");
            });
        };
    }]);

And it is getting inside search() function according to the alert("inside search"). But I am neither getting response nor failure. What am I supposed to do here?

2 Answers 2

2

You need to use .success and .error to retrieve results as per Angular http docs e.g.

$http.get('http://www.google.com').
    success(function(response) {
                $scope.data = response;
                alert("success");
            }).
    error(function(failure) {alert("failure")});
Sign up to request clarification or add additional context in comments.

1 Comment

I just checked and this is working fine. I verified using firebug tool that I am getting a json response back. But I am unable to assign it to $scope.data as I have used {{data}} in my HTML but nothing is showing up there. Could you please help me on this? Now the problem comes down to receiving the http response and showing it back to HTML page. Thanks.
1
 $http.get('www.google.com', {},
            function(response) {
                $scope.data = response;
                alert("success");
            },
            function(failure) {
                alert("failure");
});

Replace To:

$http.jsonp('http://www.google.com', {})
         .success(function(response, status) {
             $scope.data = response;
                alert("success");
        })
        . error(function(data, status) {
             alert("failure");
     });

DEMO

1 Comment

Thank you Nitish for your help. I understood now. :)

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.