Using a REST API with JS - data not outputting

I’m trying to create a simple search box to output ‘condition’ from NHS conditions API - https://developer.api.nhs.uk
I’m constantly getting an error output and a 401 when I click submit and Im sure im missing code within the simple JS script - https://codepen.io/stevan/pen/GxXorz

My api key is fine.

Well, Error 401 means your request wasnt authorized.

Your form doesnt use the AJAX request. So it’s not sending the header.

Wrap your AJAX request in a function, and call that function when you click the button. (Instead of using a submit type, just use a button and use onclick.)

The jquery .ajax function allows you to specify headers using json objects.

The data object of your request should contain the form elements. Probably serialized.

1 Like
<script type="text/javascript">
    $(function loadDoc() {
        var params = {
            // Request parameters
            "startDate": "{string}",
            "endDate": "{string}",
            "order": "{string}",
            "page": "1",
            "category": "{string}",
            "topic": "{string}",
            "orderBy": "{string}",
            "synonyms": "false",
        };
      
        $.ajax({
            url: "https://api.nhs.uk/conditions/?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("subscription-key","adf7a6b5b170405d9b258223d9cb95ef");
            },
            type: "GET",
            // Request body
            data: "{body}",
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>

Still not working… sorry a complete noob with JS and AJAX.

Check the browser’s network tab (dev tools) what you actually send. The request setup looks weird.

well that doesnt encode anything.

I will assume your button is calling loadDoc in it’s onclick.

        url: "https://api.nhs.uk/conditions/?" + $.param(params),

=>

         url: "https://api.nhs.uk/conditions/",
beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("subscription-key","actualsubscriptionkeycensored");
            },

=>

headers: {'subscription-key','yoursubscriptionkey'}
            data: "{body}",

=>

            data: params,
        })
        .done(function(data) {
            alert("success");
        })

=>

       success: function(data) {
                alert('success');
       })

Fill out params with the ACTUAL parameters you want to send.

Also the NHS could do with hiring a jquery programmer from the current decade to write their API examples.

1 Like

Oh, and while you’re at it… update your jQuery include. the 1.x branch is no longer being worked on. They’re on 3.x now.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

1 Like

It seems like the NHS API isn’t set up for CORS, and adding the custom header triggers the browser to attempt a pre-flight request, which is rejected by the API server.

Using cURL to make the request works fine, so my bet is that you’ll need a proxy (a server-side script in the language of your choice) in order to make requests to the API - although this is preferable in any case, as then you won’t be sharing your API key with the world.

2 Likes

Good point they do offer cURL and php options but before using I wanted to test out using js.

Would need an example of how to add params in {body}… any good examples for me to look at?

PS why would a 401 be called though? My api key is active.

Well without a CORS header, the simple answer is going to be ‘don’t waste your time’. You’ve reached the point of square-peg-round-hole, and will need to implement a server side script (PHP, ASP, etc) to do the requesting for you. Once you’ve got the square-to-circle converter script running, then you can worry about formatting your request to the converter.

Many thanks I’ll look at the PHP solution.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.