Using postcodes.io to retrieve post codes | post

I stumbled upon this website, where they give users to their API to search for locations etc…

I’m trying to create this on a form below, I’m new to using JSON with PHP so any pointers would be appreciated.

<?php 






if(isset($_POST['submit_me'])) {

  //API Url
  $url = 'https://api.postcodes.io/postcodes/';

  //Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
  'postcode' => 'hu5 5ag'
  
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request
$result = curl_exec($ch);



}

;?>

<form method="POST" action="index.php" class="main_form needs-validation" novalidate>  
<div class="form-row">
<div class="form-group col-md-3">
    <label for="validationCustom01">Postcode</label>
    <input type="text" class="form-control" id="validationCustom01" placeholder="Enter Postcode" name="postcode" required>
	<div class="valid-feedback">
        Looks good!
      </div>
</div>
</div>
<button type="submit" name="submit_me" class="btn btn-primary float-right">Compare Estate Agents</button>
</form>

When I submit the form it displays:

{“status”:400,“error”:“Invalid JSON query submitted. \nYou need to submit a JSON object with an array of postcodes or geolocation objects.\nAlso ensure that Content-Type is set to application/json\n”}

I’m aim to have the postcode printed out, or at least return a status 200.

Thanks
Darren


<?php

if(isset($_POST['postcode']))
{
    // Store postcode value
    $postcode = $_POST['postcode'];

    // Create a request URL, with the postcode as a parameter
    $url = 'https://api.postcodes.io/postcodes/' . $postcode;

    // Create cURL resource
    $curl = curl_init($url);

    // Set options
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    // Execute cURL request
    $response = curl_exec($curl);

    // Close cURL resource
    curl_close($curl);

    // Check for a 200 OK response
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    // If response is 200 OK, decode JSON and return
    if($http_code == 200)
    {
        $response = json_decode($response);
        echo json_encode($response);
    }
}
?>
Sponsor our Newsletter | Privacy Policy | Terms of Service