2

I am using AWS API Gateway. I want to post data to my controller which resides on my server directory. I've created one API which has a development resource and POST method. I've also added OPTIONS method to add headers.

I am using ajax to send the request data to controller. Data is always empty. Controller is in CakePHP

function which I am calling is

function webservice() {

    if(empty($this->data['username'])){

        echo json_encode("Data is Empty");
    }
    else{
        $username = $this->data['username'];
        $password = $this->data['password'];
        $deviceType =  $this->data['deviceType'];
        $token =  $this->data['token'];

        $conditions=  array('username' => $username,
                            'password' => $password,
                            'token' => $token,
                            'deviceType' => $deviceType
                            );
               echo json_encode($conditions);
    }

   exit();

    }

Ajax Call is :

var username = "dummydata";
var password = "dummydata";
var deviceType = "dummydata"
var token = "dummydata";

alert(username + password + token);
    $.ajax(
    {
    type : "POST",
    url : "https://xxxxxxxxxx.execute-api.ap-southeast-1.amazonaws.com/dev/webserv",

    data: "{username : username, password: password, token: token, deviceType: deviceType}",

    success : function(result){

         alert((result));
    }

    });

How to receive posted data from AJAX in controller using AWS API Gateway?

Jayesh
  • 71
  • 9

1 Answers1

2

First you need to provide a mapping template to API Gateway to allow it to map request data to your Lambda function call. Second, pay attention to "Content Type" you set on the mapping template, and set that same content type in your AJAX call in order to trigger the use of that template.

For example if you set the content type in API Gateway to "application/json" then you would set this property on your jQuery AJAX call: contentType: "application/json"

As for the mapping template, I find it easiest to just use a template that always maps everything from the incoming request. I use this template, taken from this answer:

{
  "method": "$context.httpMethod",
  "body" : $input.json('$'),
  "headers": {
    #foreach($param in $input.params().header.keySet())
    "$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "queryParams": {
    #foreach($param in $input.params().querystring.keySet())
    "$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "pathParams": {
    #foreach($param in $input.params().path.keySet())
    "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end

    #end
  }  
}
Community
  • 1
  • 1
Mark B
  • 183,023
  • 24
  • 297
  • 295