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
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.
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.
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.