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);
2
  • You are not parsing the result, but the XMLHttpRequest object. Commented Mar 10, 2017 at 9:45
  • Just updated the script. Commented Mar 10, 2017 at 10:01

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.