Code


<!DOCTYPE html> <html> <head> <script src="angular.js"></script> <script src="script.js"></script> <style> .logTextArea { width: 400px; height: 250px; } </style> </head> <body ng-app="mainModule"> <div ng-controller="mainController"> <h3>1. Simple GET call</h3> <button ng-click="simpleGetCall(true)">Call server with SUCCESS</button><br /> <button ng-click="simpleGetCall(false)">Call server with ERROR</button><br /> <textarea class="logTextArea">{{simpleGetCallResult}}</textarea> <br /> <h3>2. GET call with parameters</h3> <label>Parameter 1: <input type="text" ng-model="getParam1" ng-init="getParam1 = 'param1 value'" /></label><br /> <label>Parameter 2: <input type="text" ng-model="getParam2" ng-init="getParam2 = 'param2 value'" /></label><br /> <button ng-click="getCall()">GET call</button><br /> <textarea class="logTextArea">{{getCallResult}}</textarea> <br /> <h3>3. GET call with JSON response</h3> <label>Parameter 1: <input type="text" ng-model="getJSONParam1" ng-init="getJSONParam1 = 'param1 value'" /></label><br /> <label>Parameter 2: <input type="text" ng-model="getJSONParam2" ng-init="getJSONParam2 = 'param2 value'" /></label><br /> <button ng-click="getCallJSON()">GET call</button><br /> <textarea class="logTextArea">{{getCallJSONResult}}</textarea> <br /> <h3>4. GET call with timeout</h3> <button ng-click="getCallTimeout()">GET call</button><br /> <textarea class="logTextArea">{{getCallTimeoutResult}}</textarea> <br /> <h3>5. GET call with custom headers</h3> <button ng-click="getCallCustomHeaders()">GET call</button><br /> <textarea class="logTextArea">{{getCallCustomHeadersResult}}</textarea> <br /> <h3>6. GET call with transformation functions</h3> <button ng-click="getCallTransformFuncs()">GET call</button><br /> <textarea class="logTextArea">{{getCallTransformFuncsResult}}</textarea> <br /> <h3>7. POST call with parameters and data</h3> <label>Parameter 1: <input type="text" ng-model="postParam1" ng-init="postParam1 = 'param1 value'" /></label><br /> <label>Parameter 2: <input type="text" ng-model="postParam2" ng-init="postParam2 = 'param2 value'" /></label><br /> <label>Data: <input type="text" ng-model="postData" ng-init="postData = 'Custom data'" /></label><br /> <button ng-click="postCall()">POST call</button><br /> <textarea class="logTextArea">{{postCallResult}}</textarea> <br /> <h3>8. PUT call with parameters and data</h3> <label>Parameter 1: <input type="text" ng-model="putParam1" ng-init="putParam1 = 'param1 value'" /></label><br /> <label>Parameter 2: <input type="text" ng-model="putParam2" ng-init="putParam2 = 'param2 value'" /></label><br /> <label>Data: <input type="text" ng-model="putData" ng-init="putData = 'Custom data'" /></label><br /> <button ng-click="putCall()">PUT call</button><br /> <textarea class="logTextArea">{{putCallResult}}</textarea> <br /> <h3>9. DELETE call with parameters</h3> <label>Parameter 1: <input type="text" ng-model="deleteParam1" ng-init="deleteParam1 = 'param1 value'" /></label><br /> <label>Parameter 2: <input type="text" ng-model="deleteParam2" ng-init="deleteParam2 = 'param2 value'" /></label><br /> <button ng-click="deleteCall()">DELETE call</button><br /> <textarea class="logTextArea">{{deleteCallResult}}</textarea> <br /> <h3>10. HEAD call with parameters</h3> <label>Parameter 1: <input type="text" ng-model="headParam1" ng-init="headParam1 = 'param1 value'" /></label><br /> <label>Parameter 2: <input type="text" ng-model="headParam2" ng-init="headParam2 = 'param2 value'" /></label><br /> <button ng-click="headCall()">HEAD call</button><br /> <textarea class="logTextArea">{{headCallResult}}</textarea> </div> </body> </html>
angular.module("mainModule", []) .controller("mainController", function ($scope, $http, jsonFilter) { var logResult = function (str, data, status, headers, config) { return str + "\n\n" + "data: " + data + "\n\n" + "status: " + status + "\n\n" + "headers: " + jsonFilter(headers()) + "\n\n" + "config: " + jsonFilter(config); }; $scope.simpleGetCall = function (withSuccess) { var callURL = (withSuccess ? "server.php" : "invalid-url.php"); $http.get(callURL) .success(function (data, status, headers, config) { $scope.simpleGetCallResult = logResult("GET SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.simpleGetCallResult = logResult("GET ERROR", data, status, headers, config); }); }; $scope.getCall = function () { var params = { param1: $scope.getParam1, param2: $scope.getParam2 }; var config = { params: params }; $http.get("server.php", config) .success(function (data, status, headers, config) { $scope.getCallResult = logResult("GET SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.getCallResult = logResult("GET ERROR", data, status, headers, config); }); }; $scope.getCallJSON = function () { var params = { jsonObjParam: { param1: $scope.getJSONParam1, param2: $scope.getJSONParam2 } }; var config = { params: params }; $http.get("server.php", config) .success(function (data, status, headers, config) { // Since the data returned by the server is a JSON object in this case, // I use the json filter to output it as a string for debugging purposes. // The $http service automatically converts the response to a JavaScript // object whenever it sees that it looks like a JSON string. data = jsonFilter(data); $scope.getCallJSONResult = logResult("GET SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.getCallJSONResult = logResult("GET ERROR", data, status, headers, config); }); }; $scope.getCallTimeout = function () { var params = { sleep: 3 // sleep for 3 seconds before responding }; var config = { params: params, timeout: 1000 // wait at most 1 second for the response }; $http.get("server.php", config) .success(function (data, status, headers, config) { $scope.getCallTimeoutResult = logResult("GET SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.getCallTimeoutResult = logResult("GET ERROR", data, status, headers, config); }); }; $scope.getCallCustomHeaders = function () { var customHeaderFunc = function () { return "Custom header 2 from function"; }; var headers = { "Custom-Header-1": "Custom header 1 value", "My-Header-2": customHeaderFunc }; var config = { headers: headers }; $http.get("server.php", config) .success(function (data, status, headers, config) { $scope.getCallCustomHeadersResult = logResult("GET SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.getCallCustomHeadersResult = logResult("GET ERROR", data, status, headers, config); }); }; $scope.getCallTransformFuncs = function () { var customTransformRequestFunc = function (data, headersGetter) { return data; }; var customTransformResponseFunc1 = function (data, headersGetter) { return data + "\nReceived from server " + headersGetter("server"); }; var customTransformResponseFunc2 = function (data, headersGetter) { return data + "\nPROCESSING END"; }; var config = { transformRequest: customTransformRequestFunc, transformResponse: [customTransformResponseFunc1, customTransformResponseFunc2] }; $http.get("server.php", config) .success(function (data, status, headers, config) { $scope.getCallTransformFuncsResult = logResult("GET SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.getCallTransformFuncsResult = logResult("GET ERROR", data, status, headers, config); }); }; $scope.postCall = function () { var params = { param1: $scope.postParam1, param2: $scope.postParam2 }; var config = { params: params }; $http.post("server.php", $scope.postData, config) .success(function (data, status, headers, config) { $scope.postCallResult = logResult("POST SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.postCallResult = logResult("POST ERROR", data, status, headers, config); }); }; $scope.putCall = function () { var params = { param1: $scope.putParam1, param2: $scope.putParam2 }; var config = { params: params }; $http.put("server.php", $scope.putData, config) .success(function (data, status, headers, config) { $scope.putCallResult = logResult("PUT SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.putCallResult = logResult("PUT ERROR", data, status, headers, config); }); }; $scope.deleteCall = function () { var params = { param1: $scope.deleteParam1, param2: $scope.deleteParam2 }; var config = { params: params }; $http.delete("server.php", config) .success(function (data, status, headers, config) { $scope.deleteCallResult = logResult("DELETE SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.deleteCallResult = logResult("DELETE ERROR", data, status, headers, config); }); }; $scope.headCall = function () { var params = { param1: $scope.headParam1, param2: $scope.headParam2 }; var config = { params: params }; $http.head("server.php", config) .success(function (data, status, headers, config) { $scope.headCallResult = logResult("HEAD SUCCESS", data, status, headers, config); }) .error(function (data, status, headers, config) { $scope.headCallResult = logResult("HEAD ERROR", data, status, headers, config); }); }; });
<?php if ($_SERVER["REQUEST_METHOD"] === "GET") { if (isset($_GET["sleep"])) { sleep($_GET["sleep"]); } if (isset($_GET["jsonObjParam"])) { $jsonObjParam = json_decode($_GET["jsonObjParam"]); echo json_encode(array( "receivedJSONParam1" => $jsonObjParam->param1, "receivedJSONParam2" => $jsonObjParam->param2)); } else { $result = "GET request received!"; if (isset($_GET["param1"])) { $result .= "\nparam1 = " . $_GET["param1"]; } if (isset($_GET["param2"])) { $result .= "\nparam2 = " . $_GET["param2"]; } if (isset($_SERVER["HTTP_CUSTOM_HEADER_1"])) { $result .= "\nCustom-Header-1 = " . $_SERVER["HTTP_CUSTOM_HEADER_1"]; } if (isset($_SERVER["HTTP_MY_HEADER_2"])) { $result .= "\nMy-Header-2 = " . $_SERVER["HTTP_MY_HEADER_2"]; } echo $result; } } else if ($_SERVER["REQUEST_METHOD"] === "POST") { $result = "POST request received!"; if (isset($_GET["param1"])) { $result .= "\nparam1 = " . $_GET["param1"]; } if (isset($_GET["param2"])) { $result .= "\nparam2 = " . $_GET["param2"]; } if (isset($HTTP_RAW_POST_DATA)) { $result .= "\nPOST DATA: " . $HTTP_RAW_POST_DATA; } echo $result; } else if ($_SERVER["REQUEST_METHOD"] === "PUT") { $result = "PUT request received!"; if (isset($_GET["param1"])) { $result .= "\nparam1 = " . $_GET["param1"]; } if (isset($_GET["param2"])) { $result .= "\nparam2 = " . $_GET["param2"]; } $putData = file_get_contents('php://input'); if (isset($putData)) { $result .= "\nPUT DATA: " . $putData; } echo $result; } else if ($_SERVER["REQUEST_METHOD"] === "DELETE") { $result = "DELETE request received!"; if (isset($_GET["param1"])) { $result .= "\nparam1 = " . $_GET["param1"]; } if (isset($_GET["param2"])) { $result .= "\nparam2 = " . $_GET["param2"]; } echo $result; } else if ($_SERVER["REQUEST_METHOD"] === "HEAD") { $result = "HEAD request received!"; if (isset($_GET["param1"])) { $result .= "\nparam1 = " . $_GET["param1"]; } if (isset($_GET["param2"])) { $result .= "\nparam2 = " . $_GET["param2"]; } // Do something with $result. // NOTE: the HEAD method is not expected to return data, // but only the headers. } ?>

Example


Description


In case we need to make XMLHttpRequest requests to a server, AngularJS has a simple to use API for all our needs in the $http service.

In this example, we also need a server-side script to handle our requests. In this case the chosen language is PHP, but could be anything else of course. Even if you don't know PHP, the server-side part should be easy to understand.

In point 1 we start with a very simple case. It shows how we can make a GET request and how to handle a success and a failure. We can call the simpleGetCall function defined inside mainController in two ways: making it be successful or making it fail. The $http service provides a get method that accepts an URL. We can register a success handler with the success method and a failure handler with the error method. Both the methods give us some information about the server response: we have the data sent back by the server, the HTTP status, the HTTP headers of the response, the config object (we're going to talk about it later). To make it easier to see the data received in the response handler functions, we've defined the logResult function that simply prints all the data, including the JSON objects. Here we use the built-in jsonFilter to automatically print a readable version of the JSON objects and this is very useful for debugging purposes. When the simpleGetCall function is called with withSuccess = true, the server-side script server.php is requested in the URL and the call is successful, while when withSuccess = false the invalid-url.php page is requested and that file doesn't actually exist on the server so we can simulate a failure.

Now it's time to see in point 2 also how we can pass some parameters to the server while making a GET request. It turns out it's pretty simple. The get method of the $http service accepts a second parameter, the configuration object. This object is just a normal JavaScript object with some properties that let us configure the server requests before the calls are made. In this case we use the params property of the configuration object to send some parameters to the server. Here we want to send two parameters param1 and param2 and all we need to do is create an object containing all the parameter names as properties and for each property set the corresponding value, then we assign this object (called params here, but the name could be anything else) to the params property of the config object that we pass as a parameter to the get function. That's it. The server.php script will decode both parameters and send them back in a result string just to show that they've been received correctly.

In point 3 we see how we can send and receive a JSON object while communicating with a server. The getCallJSON function puts a JavaScript object called jsonObjParam (representing a JSON object) among the parameters in the configuration object of the get call. When the GET request is made, the server receives the JSON object, the server.php script decodes it and then encodes it again to send it back to the client as a response (just to show that we can actually manipulate the JSON object). When the $http service receives from the server a string that looks like a JSON object, it automatically converts it to a JavaScript object and that's what we get in the data argument of the success method. For debugging purposes, we use once again the jsonFilter to transform the data object into a JSON string representation to see it printed in the call result log.

Point 4 of the example shows that we can set a timeout in a server request. The getCallTimeout function sets a timeout of 1 second with the timeout property of the configuration object (the value of the property is expressed in milliseconds, so 1000 means 1 second) and a sleep parameter is passed to the server just to tell the server.php script that it should sleep for 3 seconds so our timeout of 1 second will make the error handler method be called.

Point 5 shows that we can send custom headers to the server by simply using the headers property of the configuration object. We need to pass an object to that property, the headers variable in this case, and each property name inside this object represents the name of a header. As you can see in the example, the value of a header can be specified as a string (the Custom header 1 value value of the Custom-Header-1 header) or as a function returning the value (the customHeaderFunc function returns the value of the My-Header-2 header). The server.php script decodes the received custom headers and sends them back as a string just to show that the values specified in the client have been received correctly by the server.

In point 6, we see that we can execute some transformation functions to manipulate the data being sent in a server request before it's actually sent and to manipulate the data received by the server in the response. We can do this with the transformRequest and the transformResponse properties of the configuration object. Here we've registered a customTransformRequestFunc function that leaves the request data as is, and an array of response manipulation functions. The functions in the array are executed in the same order they appear in the array, so customTransformResponseFunc1 is executed first and then comes the customTransformResponseFunc2. The first one shows also how we can get the value of a response header by simply using the headersGetter function available as a parameter of every transformation function.

The points 7, 8, 9 and 10 of the example simply show the other server request functions that the $http service makes available, so we have functions to make POST, PUT, DELETE and HEAD requests respectively. The post and put functions accept also a parameter to specify the data that has to be sent to the server, while the delete and head functions accept the same parameters of the get function. Note that the head function is not expected to return some data from the server so the data parameter of the success and error handler functions will always be empty.