Monday, April 11, 2016

Example of a ColdFusion web service for AngularJS using $http and JSONP

A small example of a ColdFusion JSONP Web service using $http, that expands on Ben Nadel's excellent article on Using JSONP With $resource In AngularJS.

Form Submit Code for the AngularJS Controller

$scope.onSubmit = function(){
      $http(
        {
          method: 'JSONP',
          url: 'http://your_site/your_cf_jsonp_service.cfm',
          params: {
            callback: "JSON_CALLBACK",
            data: $scope.formModel
          }
        }
      ).then(
        function successCallBack(response){console.log("returned");console.log(response);},
        function errorCallBack(response){console.log("error"); console.log(response);}
      );
  };

Sample ColdFusion AngularJS JSONP Service

<cfsetting showDebugOutput="No">
<!--- Configure the Access Control header for your environment --->
<cfheader name="Access-Control-Allow-Origin" value="*">

<cfparam name="url.callback" type="string" default="angular.callbacks_0">
<!--- Do processing logic, create objects, etc.
then serialize it
Just going to send back a time stamp for this example --->
<cfset result = Now()>
<cfset response= "#url.callback#(#serializeJson(result)#)">
<cfcontent type="text/javascript; charset=utf-8" variable="#charsetDecode(response,'utf-8')#" />

No comments:

Post a Comment