2

While there's not much available detailing what happens on the server side of a Rest API written in VBScript, there is one article that addresses this issue: Can I build a REST application using ASP Classic?. The bulk of that post describes various issues regarding JSON stringifying as well as acquiring data from a database. My question concerns neither of these. But ignoring these (and a few syntax errors), there is very little else in that post.

So, I admit to being very much of a novice regarding server-side behaviour. But when I strip away everything from the above-mentioned post, I am left with a quite bare few lines of code that appear to simply request an input value and then output a string. So I wondered if this is indeed all that is involved in the bare-bones I/O (i.e., ignoring the security and formatting issues). I decided to try this out. My results are puzzling. When I call this incredibly simple API, instead of receiving the very simple JSON string that is being sent, I instead get back the entire piece of source code comprising the API, from the opening HTML tag to its closure. I've obviously made a very fundamental error.

Here is my code. First, here is the extremely bare-bones REST API itself (please note: this is ONLY writing back an artificial JSON string. It's not even concerning itself with receiving the POST parameters.) This is "simplerest.asp"

<html>
<head>
</head>
<body>
<%
Response.Write("{" & Chr(34) & "SomeCert" & Chr(34) & ":" & Chr(34) & "12345"& Chr(34) & "}")
%>
</body>
</html>

And here is the code (utilizing jQuery) to call this "API" (testrest.asp):

<html>
<head>
<script type="text/javascript" src="/./include/jquery-3.4.1.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        function getCert(certNumber) 
        {
            var settings = {
                "async": true,
                "crossDomain": true,
                "url": "example.com/simplerest.asp",
                "method": "GET",
                "success": function (response) {
                    alert("success");
                    },
                "headers": {
                      "Accept": "application/json"
                }
            }
            $.ajax(settings).done(function (response) {
                certvals = response;
                alert("certvals is " + certvals);
            });
        }
        getCert("dummy");
    </script>
</body>
</html>

As I stated above, when I run the calling logic, what is returned in certvals is the precise ASCII representation of the entire "API" code. In the spirit of what I am attempting, which is to see an API running in its most elementary mode, can someone enlighten me as to what dumb error I am making?

user692942
  • 16,398
  • 7
  • 76
  • 175
roricka
  • 27
  • 4
  • 2
    If the output is showing the asp code and not the output, you need to enable asp first. See: [My ASP classic site is rendering the code instead of the output, how can I fix it?](https://stackoverflow.com/questions/10050074/my-asp-classic-site-is-rendering-the-code-instead-of-the-output-how-can-i-fix-i). Also, if you are giving a response as a json string, there is no need for all the tags in the page, just the code within the server tag<%%>. – Flakes Dec 05 '21 at 05:21
  • 1
    You are outputting the JSON inside a HTML page. If you are expecting raw JSON back from the server, remove the HTML and let the client know you are sending JSON by setting `Response.ContentType = "application/json"` before the `Response.Write`. – user692942 Dec 05 '21 at 08:44
  • @Flakes. Thank you. Removing the extraneous html does indeed only return the string. But I cannot parse it. If I follow user692942's advice I no longer receive success from the ajax call, but if I just do what you say, I can't parse the results. In other words, response["SomeCert"] returns as undefined. So the problem is, why doesn't `Response.ContentType = "application/json"` work here? (I found a discussion of a related point at [https://stackoverflow.com/questions/6977261/how-to-return-a-json-object-in-classic-asp/6977387] but it doesn't seem to apply here. – roricka Dec 06 '21 at 04:26
  • Yes, Classic ASP is installed on the server. Many .asp pages are functioning. Just not this experimentation with creating a REST API. – roricka Dec 06 '21 at 04:33
  • 2
    @roricka Check if there are any console errors. Also add a `Response.End` after the response.write line. I remember seing an issue sometime ago when you don't do that. Adding the `Response.ContentType = "application/json"` is the right way, as @user692942 says (also your js code has `"Accept": "application/json"`). I am getting the 12345 value when I do `alert("certvals is " + certvals.SomeCert);` – Flakes Dec 06 '21 at 05:50
  • You could try a [jQuery.getJSON()](https://api.jquery.com/jquery.getjson/) call without all the settings. – Flakes Dec 06 '21 at 08:50
  • The key is understanding what the defaults are for the [`$.ajax()`](https://api.jquery.com/Jquery.ajax/) calls in jQuery. For example, by default the `contentType` is `application/x-www-form-urlencoded; charset=UTF-8` (basically means a standard form post) and `dataType` defaults to best guess (automatic if you will), but I would recommend setting `dataType` to `json` to ensure that jQuery is expecting back a JSON structure. Would recommend reading the documentation for other caveats. – user692942 Dec 06 '21 at 09:30
  • Also, setting the accept header manually is something I wouldn't recommend, use the built-in properties to let jQuery handle setting those headers itself. In fact, if you can use a web sniffer like [Fiddler](https://www.telerik.com/fiddler) to check the requests or even just the network tab in dev tools in the Browser. – user692942 Dec 06 '21 at 09:33
  • Yes, the accept header ultimately was the main problem. My original code benefitted in several ways by the solutions offered (although putting the – user1693404 Dec 14 '21 at 18:30
  • 1
    It is worth noting that, if you're _creating_ a REST API using asp classic (as in, you're not having to work with legacy projects) , you _should_ create it with newer, non obsolete stacks, such as .NET Core. – Eric Wu Dec 24 '21 at 14:57

1 Answers1

3

Assuming you have Classic ASP installed and enabled in your website (IIS), use;

<%
'Tell client you are sending JSON
Response.ContentType = "application/json"
Call Response.Write("{""SomeCert"":""12345""}")
%>

Because you had the JSON encapsulated in a HTML structure it was just being output as a string in the HTML page.

Also, there is no need for Chr(34) when you can escape double quotes in strings by doubling them.


In regard to the comments, here is a fully working example tested using a local instance of IIS.

<html>
  <head>
    <title></title>
  </head>
  <body>
    <button id="buttonSend">Send</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script>
      $("#buttonSend").on("click", function() {
        getCert("dummy");
      });

      function getCert(certNumber) 
      {
        var settings = {
          "async": true,
          "crossDomain": true,
          "url": "example.com/simplerest.asp",
          "method": "GET",
          "success": function (response) {
            alert("success");
          }
        }
        $.ajax(settings).done(function (response) {
          certvals = response;
          alert("certvals is " + certvals.SomeCert);
        });
      }
    </script>
  </body>
</html>

Outputs (two messages):

success
certval is 12345

Useful Links

user692942
  • 16,398
  • 7
  • 76
  • 175
  • Thanks you, this works. (But shouldn't the script tags be INSIDE either the or ?) Ultimately, my error was to include the accept header. Once I removed that the original code worked, albeit without some of the niceties some folks added. Thank you very much. – roricka Dec 14 '21 at 18:45
  • @roricka yes they should, will correct that. Glad it was useful. – user692942 Dec 14 '21 at 22:41