0

I am trying to test Google Cloud analyzeSyntax from JavaScript, forming an ajax request using jQuery, but I keep getting errors returned. I obviously don't understand how to form the call properly but cannot find any answers or examples that match what I am trying to do.

The documentation for the call is https://cloud.google.com/natural-language/docs/reference/rest/v1/documents/analyzeSyntax.

HTML

<!DOCTYPE html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="pm.js"></script>
  </head>

  <body>
    <button onclick="analyzeSyntax();">Go</button>
    <div id="results"></div>
  </body>
</html>

JS

function analyzeSyntax() {
  $.ajax({
    type: "POST",
    url: "https://language.googleapis.com/v1/documents:analyzeSyntax?key=XXXXXXXXXXXXX",
    data: { "document" : {
      "type":"PLAIN_TEXT",
      "content":"I just want to try out analyzeSyntax",
      },
      encodingType: "UTF8"   
    },         
    success: function(data){
      alert("success " + data.responseText);
    },
    error: function(data){
     alert("error " + data.responseText);
    }
  });
}

ERROR

"error": {
  "code": 400,
  "message": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message.",
  "status": "INVALID_ARGUMENT",
  "details": [
    {
      "@type": "type.googleapis.com/google.rpc.BadRequest",
      "fieldViolations": [
        {
          "description": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message."
        },
        {
          "description": "Invalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message."
        }
      ]
    }
  ]
}
essensian
  • 1
  • 1
  • 1
    Have you tried to JSON.stringify() the data object before executing the request? – user3821538 Aug 20 '18 at 19:42
  • As [user3821538](https://stackoverflow.com/users/3821538/user3821538) mentioned, you need to transform your payload to JSON explicitly in jQuery. See this [question and answer](https://stackoverflow.com/questions/5570747/jquery-posting-json) for more details. – JSTL Aug 20 '18 at 20:08
  • Possible duplicate of [jQuery posting JSON](https://stackoverflow.com/questions/5570747/jquery-posting-json) – JSTL Aug 20 '18 at 20:08
  • That was it. Thank you, thank you, thank you both user3821538 and JSTL. – essensian Aug 21 '18 at 08:24

0 Answers0