1

I'm trying to do a UK Postcode validation using JS by connecting to http://postcodes.io/ post code validation service.

When I post to api.postcodes.io/postcodes/POSTCODEVARIABLE/validate I should recieve a 200 response and result of either "True" or "False" depending on whether the postcode is valid or not.

However, when I try to receive the data (in JSON format) I get an error in the console:

 "Uncaught SyntaxError: Unexpected token o in JSON at position 1"

Here is my code, if anyone could point out where I am going wrong, that would be great.

var cpostcode = 'RG1 8BT';
var cpostcode = cpostcode.replace(/\s+/g, '');
var myNewURL = 'https://api.postcodes.io/postcodes/' + cpostcode + '/validate';

var pcapi = new XMLHttpRequest();


pcapi.onreadystatechange = function() {
if (pcapi.readyState == XMLHttpRequest.DONE) {
    alert(pcapi.responseText);
    }
}

pcapi.open("GET", myNewURL, true);
pcapi.send(null);

var xyz = JSON.parse(pcapi);

console.log(xyz);
Sam Allen
  • 589
  • 4
  • 6
  • 16

1 Answers1

1

Like at @Youssef said you want to log the .responseText. You get that script error because pcapi is a XMLHttpRequest object and not valid json which JSON.parse() attempts to parse. If you want to learn more about what you can do with the pcapi object just console.log(pcapi) and you can see its {keys:values} or just read up on it.

JSON.parse() converts any JSON String passed into the function, to a JSON Object.

There is really no such thing as a "JSON Object". The JSON spec is a syntax for encoding data as a string. ... JSON is a subset of the object literal notation of JavaScript. In other words, valid JSON is also valid JavaScript object literal notation but not necessarily the other way around. - stackoverflow

var cpostcode = 'RG1 8BT';
var cpostcode = cpostcode.replace(/\s+/g, '');
var pcapi = new XMLHttpRequest();

var myNewURL = 'https://api.postcodes.io/postcodes/' + cpostcode + '/validate';

pcapi.open("GET", myNewURL, false);
pcapi.send();

var xyz = JSON.parse(pcapi.responseText);

console.log(xyz);
Community
  • 1
  • 1
Jonathan Portorreal
  • 2,730
  • 4
  • 21
  • 38