POST request to the backend service

4337
25
03-05-2018 03:40 PM
MansiShah
New Contributor III

Hello,

I am modifying an existing Web App Builder template and in order to complete the functionality of a widget I need it to make a connection to a backend service. When I pull up the service url, a form comes up that needs to be filled. I have the information for the form stored in a JSON. I want to pass that to the backend but I am getting errors on how to make the POST request. 

Here is what I've tried inside of a function: 

  $.ajax({
                method: "POST",
                url: "url to the backend service",
                data: jobIds,
                dataType: "json",
                success: function(){
                    console.log("Success!");
                }
            });
I have also tried to add the "dojo/request" and "dojo/json" dependencies but those give me errors and won't even let the widget start.
Have anyone else encountered this? Or is there another way to POST request and get a response from a backend service different from what I've coded up?
Thank you!!
0 Kudos
25 Replies
MansiShah
New Contributor III

When I comment out the esriRequest code, I don't get that error anymore. 

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

The jobids var. Can you show some of your code to build this var?

0 Kudos
MansiShah
New Contributor III

Several functions and several parts of the code are involved in creating that object but I am logging the stringified version of the object to the console which is: 

{"id":null,"name":null,"autoCommitWorkflow":null,"autoExecute":null,"poi":null,"parentjobid":null,"dataworkspaceid":null,"parentversion":null,"jobTypeId":33,"startDate":"2018-03-11T05:00:00.000Z","dueDate":"2018-03-11T05:00:00.000Z","priority":"0","description":"test app1. ","ownedBy":"mshah.dev","assignedType":1,"assignedTo":"mshah.dev","numJobs":1,"user":"mshah.dev","aoi":[{"type":"polygon","rings":[[[13.27139454350854,29.56717206138049],[11.689542956287314,29.56717206138049],[11.689542956287314,30.02464354338104],[13.27139454350854,30.02464354338104],[13.27139454350854,29.56717206138049]]],"_ring":0,"spatialReference":{"wkid":4326},"cache":{"_extent":{"xmin":11.689542956287314,"ymin":29.56717206138049,"xmax":13.27139454350854,"ymax":30.02464354338104,"spatialReference":{"wkid":4326}},"_partwise":null}}]}

when I put that in a JSON formatter it does not give me errors and the properties it has are the fields in my form in the backend service that I need to fill out. 

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Mansi,

  Here is what your request would look like for a REST service that takes one input parameter:

            var createdJob = esriRequest(url, {
                "query" : {
                  yourinputparametername: jobIds
                },
                "callbackParamName": "callback",
                "usePost" : true,
                "handleAs" : "json"
            }).then(function(response){
                console.log("The response is : ", response);
            });‍‍‍‍‍‍‍‍‍‍

Here is some sample code using one of my REST services and how it looks:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
  <title>Request data from a remote server - 4.6</title>

  <style>
    html,
    body,
    #viewDiv {
      font-family: sans-serif;
      padding: 0;
      margin: 0;
      height: 100%;
      width: 100%;
    }

    .container {
      padding: 1em;
    }

    input {
      width: 75%;
    }
  </style>

  <link rel="stylesheet" href="https://js.arcgis.com/4.6/esri/css/main.css">
  <script src="https://js.arcgis.com/4.6/"></script>

  <script>
    require([
      "esri/request",
      "dojo/on",
      "esri/config",
      "dojo/domReady!"
    ], function(
      esriRequest,
      on,
      esriConfig
    ) {
      esriConfig.request.proxyUrl = 'proxy/proxy.ashx';
      var resultsDiv = document.getElementById("resultsDiv");
      var input = document.getElementById("inputUrl");

      /************************************************
       *
       * Define the 'options' for our request.
       *
       *************************************************/
      var options = {
        query: {
//my REST service requires one input parameter named ppin.
          ppin: input.value,
          f: 'json'
        },
        responseType: 'json'
      };

      // Make the request on a button click using the
      // value of the 'input' text.
      on(btnQuery, "click", function() {
        var url = 'http://myserver/service/method';
        esriRequest(url, options).then(function(response) {
          console.log('response', response);
          var responseJSON = JSON.stringify(response, null, 2);
          resultsDiv.innerHTML = responseJSON;
        });
      });
    });
  </script>
</head>

<body>
  <div class="container">
    <div>
      <h2>Using esri/request</h2>
      <button id="btnQuery">Make Request</button>
      <input id="inputUrl" type="text" value="1998">
    </div>
    <pre id="resultsDiv"></pre>
  </div>
</body>

</html>‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
MansiShah
New Contributor III

Robert,

I don't understand what the "yourinputparametername" property stands for? I have a form in my rest service that I can pull up because of a specific url but I don't see anywhere where it would specify the asking for an input parameter. Is this just a name that I make up?

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Mansi,

   This is going to depend on how familiar you are with the REST service. I created the rest service In my sample so I know it takes a input called ppin based on the .Net code:

<WebGet(UriTemplate:="/gettaxbill?ppin={ppin}", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Bare)>
  Public Function GetTaxBill(Optional ByVal ppin As String = "1234") As taxBill
0 Kudos
MansiShah
New Contributor III

Robert, 

I have made modifications to the query parameter/property for it to suit our backend, but I now keep getting the following error:

SyntaxError: Unexpected token <
at Object.b.fromJson (init.js:131)
at Object.json (init.js:84)
at r (init.js:88)
at c (init.js:103)
at d (init.js:103)
at b.Deferred.resolve.callback (init.js:105)
at init.js:92
at l (init.js:107)
at t (init.js:107)
at d.resolve (init.js:109)

do you recognize this error by any chance? I have not been able to find the same error online but in another similar error with a different token, someone mentioned that the response coming back was not a proper json. I tested our backend but manually filling out the service form and the response I see online after hitting submit is a proper JSON. Do you possibly have any idea for what this error could be or have you encountered it before?

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Where in tour code do you get this error in the esriRequest callback function?

0 Kudos
MansiShah
New Contributor III

My code is this: 

var url = "url to backend";
            console.log("after the url has been defined. in create new job");

            var createdJob = esriRequest({
                'url' : url,
                'query' : {
                    user: jobSettings.user,
                    jobtypeid: jobSettings.jobtypeid,
                    id : jobSettings.id,
                    name : jobSettings.name,
                    startdate : jobSettings.startdate,
                    duedate : jobSettings.duedate,
                    priority: jobSettings.priority,
                    parentjobid : jobSettings.parentjobid,
                    dataworkspaceid : jobSettings.dataworkspaceid,
                    parentversion : jobSettings.parentversion,
                    description : jobSettings.description,
                    ownedby : jobSettings.ownedby,
                    assignedtype : jobSettings.assignedtype,
                    assignedto : jobSettings.assignedto,
                    aoi : jobSettings.aoi,
                    poi : jobSettings.poi,
                    numjobs : jobSettings.numjobs,
                    autocommitworkflow : jobSettings.autocommitworkflow,
                    autoexecute : jobSettings.autoexecute,
                    f : 'json'
                },
                'callbackParamName' : 'callback',
                'usePost' : true,
                'handleAs' : 'json',
                'responseType' : 'json'
            }).then(function(response){
                console.log("The response is: ", response);
            }); 

            console.log("End of createNewJob()"); 
The code will log "End of createNewJob()" to the console and then give me the error I talked about earlier:
init.js:89 SyntaxError: Unexpected token <
at Object.b.fromJson (init.js:131)
at Object.json (init.js:84)
at r (init.js:88)
at c (init.js:103)
at d (init.js:103)
at b.Deferred.resolve.callback (init.js:105)
at init.js:92
at l (init.js:107)
at t (init.js:107)
at d.resolve (init.js:109)
So when I hit the "Create Job" button, it will go through the whole createNewJob() function and then give me this error in the end but when I take away my esriRequest code, I do not get that error at all. So I am sure it has something to do with this piece of code. I would like to at least see what is being returned so I can see how I would need to modify the code in case the JSON being returned in not being recognized as a JSON. But I can't figure out how I would do that? I have tried adding the following to the code:
 
createdJob.then(
                function(data){
                    console.log("Success: ", data)
                },
                function(error){
                    console.log("Error!!");
                }
            );
When I run the application with this code, it will log "End of createNewJob()" first to the console and then the error will show up in red and then "Error!!" will be logged??
0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Mansi,

  This seems more like a problem with your REST service then your JS code to use it.

0 Kudos